PIVOT
在 10g 中尚不可用(它仅出现在 11g 中,并且在 techdo 的答案中显示),所以你必须解决这个问题。这是一种可能的方法:
SQL小提琴
Oracle 11g R2 模式设置:
CREATE TABLE DATA
("Y" int, "M" int, "V" int)
;
INSERT ALL
INTO DATA ("Y", "M", "V")
VALUES (2013, 01, 45665)
INTO DATA ("Y", "M", "V")
VALUES (2013, 02, 2364)
INTO DATA ("Y", "M", "V")
VALUES (2013, 03, 98736)
INTO DATA ("Y", "M", "V")
VALUES (2013, 04, 6623541)
INTO DATA ("Y", "M", "V")
VALUES (2013, 05, 9856)
INTO DATA ("Y", "M", "V")
VALUES (2012, 02, 23102)
INTO DATA ("Y", "M", "V")
VALUES (2012, 06, 10002)
INTO DATA ("Y", "M", "V")
VALUES (2012, 07, 120)
SELECT * FROM dual
;
查询 1:
select
y
,max(m1) m1
,max(m2) m2
,max(m3) m3
,max(m4) m4
,max(m5) m5
,max(m6) m6
,max(m7) m7
,max(m8) m8
,max(m9) m9
,max(m10) m10
,max(m11) m11
,max(m12) m12
from (
select
y
,decode(m, 1, v) m1
,decode(m, 2, v) m2
,decode(m, 3, v) m3
,decode(m, 4, v) m4
,decode(m, 5, v) m5
,decode(m, 6, v) m6
,decode(m, 7, v) m7
,decode(m, 8, v) m8
,decode(m, 9, v) m9
,decode(m, 10, v) m10
,decode(m, 11, v) m11
,decode(m, 12, v) m12
from data
) t
group by y
结果:
| Y | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | M9 | M10 | M11 | M12 |
--------------------------------------------------------------------------------------------------------------------
| 2013 | 45665 | 2364 | 98736 | 6623541 | 9856 | (null) | (null) | (null) | (null) | (null) | (null) | (null) |
| 2012 | (null) | 23102 | (null) | (null) | (null) | 10002 | 120 | (null) | (null) | (null) | (null) | (null) |