NO | MONEY | DAY |
1 | 23 | 1 |
1 | 43 | 2 |
1 | -45 | 3 |
2 | 42 | 1 |
2 | -10 | 2 |
2 | 50 | 3 |
3 | 100 | 8 |
為了符合閱讀習慣,最終報表希望是如下格式:
NO | MON | TUE | THR |
1 | 23 | 43 | -45 |
2 | 42 | -10 | 50 |
3 |
------------------------
咱們一步步來實現(xiàn):
1.運用DECODE轉換行為列
SQL:
SELECT NO,
DECODE(DAY,1,MONEY,'') DAY1,
DECODE(DAY,2,MONEY,'') DAY2,
DECODE(DAY,3,MONEY,'') DAY3
FROM TEMP
結果:
NO | DAY1 | DAY2 | DAY3 |
1 | 23 | ||
1 | 43 | ||
1 | -45 | ||
2 | 42 | ||
2 | -10 | ||
2 | 50 | ||
3 |
2.按NO字段分組,并更改列名
SQL:
SELECT NO, MAX(DAY1) MON, MAX(DAY2) TUE, MAX(DAY3) THR
FROM (SELECT NO,
DECODE(DAY, 1, MONEY,'') DAY1,
DECODE(DAY, 2, MONEY,'') DAY2,
DECODE(DAY, 3, MONEY,'') DAY3
FROM TEMP)
GROUP BY NO;
結果:
NO | MON | TUE | THR |
1 | 23 | 43 | -45 |
2 | 42 | -10 | 50 |
3 |
------------------------
重難點歸納:
1.DECODE缺省值設置
DECODE語法如下:decode(條件,值1,翻譯值1,值2,翻譯值2,...值n,翻譯值n,缺省值)
如果缺省值由''(兩個單引號)改為0,即SQL:
SELECT NO, MAX(DAY1) MON, MAX(DAY2) TUE, MAX(DAY3) THR
FROM (SELECT NO,
DECODE(DAY, 1, MONEY,0) DAY1,
DECODE(DAY, 2, MONEY,0) DAY2,
DECODE(DAY, 3, MONEY,0) DAY3
FROM TEMP)
GROUP BY NO;
結果如下(所有值為負與空值都被賦為0):
NO | MON | TUE | THR |
1 | 23 | 43 | 0 |
2 | 42 | 0 | 50 |
3 | 0 | 0 | 0 |
2.列缺省值設置(DAY值為8的顯示為'undefined')
SQL:
SELECT NO,MONEY,
DECODE(DAY,1,'MON',2,'TUE',3,'THR','undefined') DAY
FROM TEMP
結果:
NO | MONEY | DAY |
1 | 23 | MON |
1 | 43 | TUE |
1 | -45 | THR |
2 | 42 | MON |
2 | -10 | TUE |
2 | 50 | THR |
3 | 100 | undefined |
3.行列轉化在表單內數(shù)據(jù)量較大的情況下消耗較大
原因:
1.掃描目標數(shù)據(jù)時間開銷大。
2.GROUP BY時,數(shù)據(jù)冗余帶來的多行合并。
優(yōu)點:
表結構穩(wěn)定:DAY增加新值只需增加記錄,無需新增新列!
下一頁 decode()函數(shù)使用技巧