ORACLE 中 DECODE函數的用法

1、語法格式

decode(條件,值1,翻譯值1,值2,翻譯值2,...值n,翻譯值n,缺省值)


2、函數解釋:
IF 條件=值1 THEN
    RETURN(翻譯值1)
ELSIF 條件=值2 THEN
    RETURN(翻譯值2)
    ......
ELSIF 條件=值n THEN
    RETURN(翻譯值n)

ELSE
    RETURN(缺省值)

END IF


3、使用方法: 
1)比較大小
select decode(sign(變量1-變量2),-1,變量1,變量2) from dual; --取較小值
sign()函數根據某個值是0、正數還是負數,分別返回0、1、-1
例如:
變量1=10,變量2=20

則sign(變量1-變量2)返回-1,decode解碼結果爲“變量1”,達到了取較小值的目的。

2)表、視圖結構轉化
舉例1:現有一個商品銷售表sale,表結構爲:

現有數據爲:

想要轉化爲以下結構的數據:

結構轉化的SQL語句爲:
create or replace view
v_sale(year,month1,month2,month3,month4,month5,month6,month7,month8,month9,month10,month11,month12)
as
    select 
    substr(month,1,4) as 年份,
    sum(decode(substr(month,5,2),'01',sell,0)) AS 一月,
    sum(decode(substr(month,5,2),'02',sell,0)) AS 二月,
    sum(decode(substr(month,5,2),'03',sell,0)) AS 三月,
    sum(decode(substr(month,5,2),'04',sell,0)) AS 四月,
    sum(decode(substr(month,5,2),'05',sell,0)) AS 五月,
    sum(decode(substr(month,5,2),'06',sell,0)) AS 六月,
    sum(decode(substr(month,5,2),'07',sell,0)) AS 七月,
    sum(decode(substr(month,5,2),'08',sell,0)) AS 八月,
    sum(decode(substr(month,5,2),'09',sell,0)) AS 九月,
    sum(decode(substr(month,5,2),'10',sell,0)) AS 十月,
    sum(decode(substr(month,5,2),'11',sell,0)) AS 十一月,
    sum(decode(substr(month,5,2),'12',sell,0)) AS 十二月
    from aa_cs
    group by substr(month,1,4); 

舉例2:從我自己做過的項目中摘取的一個實例,目的是對錶記錄進行分析打印

表結構:



SQL語句:

select 
 e.equi_type,
ty1.type_name,
 e.equi_cd,
e.equi_name,
 count(m.equi_cd) as m_count,
  (sum(decode(m.maintain_type, '0001', m.total_cost, 0))) AS type1,
  (sum(decode(m.maintain_type, '0002', m.total_cost, 0))) AS type2,
  (sum(decode(m.maintain_type, '0003', m.total_cost, 0))) AS type3,
  (sum(decode(m.maintain_type, '0004', m.total_cost, 0))) AS type4,
  (sum(decode(m.maintain_type, '',0,m.total_cost))) AS TOTAL_COST 
from equi_maintain m
left join equi_equipment e on m.equi_cd=e.id
left join equi_type ty1 on e.equi_type=ty1.id
group by  e.EQUI_CD,e.equi_name,e.equi_type,ty1.type_name order by e.EQUI_CD asc 
顯示效果爲:



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章