透视表SQL

时间:2018-12-04 13:42:01

标签: mysql sql pivot

我有这张桌子:

|............id.............|............a............. |.............b............|
|...........123qwe....      |...........0.............  |.............13...........|

我需要像这样旋转它:

|.........id................|........indicator....      |.............value........ |
|...........123qwe....      |...........a.............  |.............0.............|
|...........123qwe....      |...........b.............  |.............13........... |

有超过100列带有指示符的标头(a,b,c,d,e,f,...),因此需要一种循环。

2 个答案:

答案 0 :(得分:1)

 SELECT id, 'a', SUM(a)
 FROM yourtable
 GROUP BY id
 UNION 
 SELECT id, 'b', SUM(b)
 FROM yourtable
 GROUP BY id
 UNION
 ...

通常,正确答案是使您的模式规范化。

答案 1 :(得分:0)

这样做:

SELECT id, 'a' AS indicator, a AS value
FROM test
UNION
SELECT id, 'b' AS indicator, b AS value
FROM test;

如果要循环,最好将其编写在程序中...