Oracle数据库中实现“多行一列”转“一行多列”
程序员文章站
2022-03-31 21:39:06
...
Oracle数据库内数据大多按行存储,以测试数据样式为例:
YM | NUM |
---|---|
202001 | 15 |
202002 | 5 |
202003 | 12 |
202004 | 7 |
202005 | 9 |
202006 | 12 |
202007 | 8 |
202008 | 1 |
202009 | 2 |
202010 | 3 |
202011 | 13 |
202012 | 6 |
自己随手在数据库内建的数据,每个月对应一个数量,如果想要展示成一行多列:数据202001|数据202002|数据202003|数据202004|数据202005|数据202006|数据202007|数据202008|数据202009|数据202010|数据202011|数据202012|
sql如下:
SELECT
sum(CASE WHEN YM='202001' THEN num end) AS 数据202001,
sum(CASE WHEN YM='202002' THEN num end) AS 数据202002,
sum(CASE WHEN YM='202003' THEN num end) AS 数据202003,
sum(CASE WHEN YM='202004' THEN num end) AS 数据202004,
sum(CASE WHEN YM='202005' THEN num end) AS 数据202005,
sum(CASE WHEN YM='202006' THEN num end) AS 数据202006,
sum(CASE WHEN YM='202007' THEN num end) AS 数据202007,
sum(CASE WHEN YM='202008' THEN num end) AS 数据202008,
sum(CASE WHEN YM='202009' THEN num end) AS 数据202009,
sum(CASE WHEN YM='202010' THEN num end) AS 数据202010,
sum(CASE WHEN YM='202011' THEN num end) AS 数据202011,
sum(CASE WHEN YM='202012' THEN num end) AS 数据202012
FROM csdn_case
WHERE YM BETWEEN '202001' AND '202012'
最终展示效果如下:
数据202001|数据202002|数据202003|数据202004|数据202005|数据202006|数据202007|数据202008|数据202009|数据202010|数据202011|数据202012|
--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+
10| 10| 12| 10| 9| 12| 9| 12| 12| 9| 12| 9|
如果不写sum,会出现多行数据,做不到一行多列的效果。
此种情况是针对表里已经有明确的数据了,如果表里没有,还需要自己去数的话,就把Sum改成count distinct即可。