decode(條件,值1,翻譯值1,值2,翻譯值2,...值n,翻譯值n,缺省值)
該函數的含義以下:
IF 條件=值1 THEN
RETURN(翻譯值1)
ELSIF 條件=值2 THEN
RETURN(翻譯值2)
......
ELSIF 條件=值n THEN
RETURN(翻譯值n)
ELSE
RETURN(缺省值)
END IF
· 使用方法:
一、比較大小
select decode(sign(變量1-變量2),-1,變量1,變量2) from dual; --取較小值
sign()函數根據某個值是0、正數仍是負數,分別返回0、一、-1
例如:
變量1=10,變量2=20
則sign(變量1-變量2)返回-1,decode解碼結果爲「變量1」,達到了取較小值的目的。
二、表、視圖結構轉化
現有一個商品銷售表sale,表結構爲:
month char(6) --月份
sell number(10,2) --月銷售金額
現有數據爲:
200001 1000
200002 1100
200003 1200
200004 1300
200005 1400
200006 1500
200007 1600
200101 1100
200202 1200
200301 1300
想要轉化爲如下結構的數據:
year char(4) --年份
month1 number(10,2) --1月銷售金額
month2 number(10,2) --2月銷售金額
month3 number(10,2) --3月銷售金額
month4 number(10,2) --4月銷售金額
month5 number(10,2) --5月銷售金額
month6 number(10,2) --6月銷售金額
month7 number(10,2) --7月銷售金額
month8 number(10,2) --8月銷售金額
month9 number(10,2) --9月銷售金額
month10 number(10,2) --10月銷售金額
month11 number(10,2) --11月銷售金額
month12 number(10,2) --12月銷售金額
結構轉化的SQL語句爲:
create or replace view
v_sale(year,month1,month2,month3,month4,month5,month6,month7,month8,month9,month10,month11,month12)
as
select
substrb(month,1,4),
sum(decode(substrb(month,5,2),'01',sell,0)),
sum(decode(substrb(month,5,2),'02',sell,0)),
sum(decode(substrb(month,5,2),'03',sell,0)),
sum(decode(substrb(month,5,2),'04',sell,0)),
sum(decode(substrb(month,5,2),'05',sell,0)),
sum(decode(substrb(month,5,2),'06',sell,0)),
sum(decode(substrb(month,5,2),'07',sell,0)),
sum(decode(substrb(month,5,2),'08',sell,0)),
sum(decode(substrb(month,5,2),'09',sell,0)),
sum(decode(substrb(month,5,2),'10',sell,0)),
sum(decode(substrb(month,5,2),'11',sell,0)),
sum(decode(substrb(month,5,2),'12',sell,0))
from sale
group by substrb(month,1,4);
此函數用在SQL語句中,功能介紹以下: 函數
DECODE函數與一系列嵌套的 IF-THEN-ELSE語句類似。base_exp與compare1,compare2等等依次進行比較。若是base_exp和 第i 個compare項匹配,就返回第i 個對應的value 。若是base_exp與任何的compare值都不匹配,則返回default。每一個compare值順次求值,若是發現一個匹配,則剩下的compare值(若是還有的話)就都再也不求值。一個爲NULL的base_exp被認爲和NULL compare值等價。若是須要的話,每個compare值都被轉換成和第一個compare 值相同的數據類型,這個數據類型也是返回值的類型。 spa
DECODE函數在實際開發中很是的有用 翻譯
結合LPAD函數,如何使主鍵的值自動加1並在前面補0
select LPAD(decode(count(記錄編號),0,1,max(to_number(記錄編號)+1)),14,'0') 記錄編號
from tetdmis.zf_鑽井日報表 code