简体   繁体   中英

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.

 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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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