Oracle函數Decode

一、Decode()

假設我們想給職員加工資,其標準是:工資在8000元以下的將加20%;工資在8000元以上的加15%

通過SQL語句就可以直接完成:select decode(sign(salary - 8000),1,salary*1.15,-1,salary*1.2,salary from employee

DECODE的語法:DECODE(value,if1,then1,if2,then2,if3,then3,...,else),表示如果value等於if1時,DECODE函數的結果返回then1,...,如果不等於任何一個if值,則返回else

 

使用方法:

  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、表、視圖結構轉化

  現有一個商品銷售表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月銷售金額

                        ……

    結構轉化的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)),

                       ……

發佈了22 篇原創文章 · 獲贊 4 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章