我在表中有数据,如下所示:
MONTH VALUE 1 100 2 200 3 300 4 400 5 500 6 600
我想编写一个SQL查询,以便给出如下结果:
MONTH_JAN MONTH_FEB MONTH_MAR MONTH_APR MONTH_MAY MONTH_JUN 100 200 300 400 500 600
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
您只列出了两列-可能应按年份将类似的内容分组。
有ANSI PIVOT(和UNPIVOT)语法,但是Oracle直到11g才支持它。在9i之前,您必须将CASE语句替换为Oracle特定的DECODE。