Oracle SQL pivot query

前端 未结 2 1625
面向向阳花
面向向阳花 2020-11-22 04:10

I have data in a table as seen below:

MONTH VALUE

1     100
2     200
3     300
4     400
5     500
6     600

I want to write a SQL query

2条回答
  •  一向
    一向 (楼主)
    2020-11-22 04:49

    Oracle 9i+ supports:

    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.

    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.

提交回复
热议问题