oracle decode()__oracle

來源:互聯網
上載者:User

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 
· 使用方法: 
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月銷售金額 
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)), 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.