简体   繁体   English

透视表SQL

[英]Pivoting table sql

I have this table: 我有这张桌子:

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

and I need to pivot it like this: 我需要像这样枢纽一下:

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

There are more thatn 100 columns with indicators as headers (a,b,c,d,e,f,...) so a sort of loop would be needed. 超过100列带有指示符的标头(a,b,c,d,e,f,...),因此将需要某种循环。

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

As usual, the right answer is to normalize you schema. 像往常一样, 正确的答案是规范您的架构。

Do it like this: 像这样做:

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

and if you want loop, you'd better write it in the program... 如果要循环,最好将其编写在程序中...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM