date1 tran_1 date2 tran_2 date3 tran_3 ..... date80 tran_80
may01 24 jun02 32 aug18 56 ..... sep10 44
Sep01 24 Nov08 32 Jan18 56 ..... Jun18 44
现在输出应该是如何编写动态查询..我已经通过传递参数编写了一个过程,对于上述 80 个变量我必须调用该过程大约 40 次,请帮助我
date tran type
may01 24 tran_1
Sep01 24 tran_1
jun02 32 tran_2
Nov08 32 tran_2
aug18 56 tran_3
Jan18 56 tran_3
........................
........................
sep10 44 tran_80
Jun18 44 tran_80
最佳答案
一种方法是只使用union all
:
select date, tran_1 as tran, 'tran_1' as type from t union all
select date, tran_2 as tran, 'tran_2' as type from t union all
select date, tran_3 as tran, 'tran_3' as type from t union all
. . .
我的建议是在电子表格中生成代码。只需生成数字 1 到 80 并使用电子表格功能。或者,如果您不想在其中键入所有列名,则可以生成动态 SQL。
如果性能是一个问题并且您有大量数据,还有其他方法。然而,这种类型的查询通常只运行一次,更难构建更高效的查询。
关于mysql - 如何合并同一个表中的每 2 个连续列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32990577/