且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Oracle SQL数据透视查询

更新时间:2023-01-21 10:43:19

Oracle 9i +支持:

SELECT SUM(CASE WHEN t.month = 1 THEN t.value ELSE 0 END) AS JAN,
       SUM(CASE WHEN t.month = 2 THEN t.value ELSE 0 END) AS FEB,
       SUM(CASE WHEN t.month = 3 THEN t.value ELSE 0 END) AS MAR,
       SUM(CASE WHEN t.month = 4 THEN t.value ELSE 0 END) AS APR,
       SUM(CASE WHEN t.month = 5 THEN t.value ELSE 0 END) AS MAY,
       SUM(CASE WHEN t.month = 6 THEN t.value ELSE 0 END) AS JUN
  FROM YOUR_TABLE t

您仅列出两列-可能应按年份将类似的内容分组.

You only list two columns -- something like this should probably be grouped by year.

有ANSI PIVOT(和UNPIVOT)语法,但是Oracle直到11g才支持它.在9i之前,您必须将CASE语句替换为Oracle特定的DECODE.

There is ANSI PIVOT (and UNPIVOT) syntax, but Oracle didn't support it until 11g. Prior to 9i, you'd have to replace the CASE statements with Oracle specific DECODE.