SQL中 decode() 函數介紹


decode() 函數的語法:

1 Select decode(columnname,值1,翻譯值1,值2,翻譯值2,...值n,翻譯值n,缺省值) 2 
3 From talbename 4 
5 Where

其中:columnname為要選擇的table中所定義的column;

   缺省值可以是你要選擇的column name本身,也可以是你想定義的其他值,比如Other等;

主要作用:相當於IF語句, 將查詢結果翻譯成其他值。(即以其他形式表現出來)。

 

舉例說明:

現定義一table名為output,其中定義兩個column分別為monthid(var型)和sale(number型),若sale值=1000時翻譯為D,=2000時翻譯為C,=3000時翻譯為B,=4000時翻譯為A,如是其他值則翻譯為Other:

Select monthid , decode (sale,1000,'D',2000,'C',3000,'B',4000,'A',’Other’) sale from output

若只與一個值進行比較:

Select monthid ,decode(sale, NULL‘---’,sale) sale from output

 

decode中可使用其他函數,如nvl()函數或sign()函數等:

  NVL(EXPR1,EXPR2)

  若EXPR1是NULL,則返回EXPR2,否則返回EXPR1。

SELECT NAME,NVL(TO_CHAR(COMM),'NOT APPLICATION') FROM TABLE1;

如果用到decode函數中:

select monthid,decode(nvl(sale,6000),6000,'NG','OK') from output;

 

  sign()函數根據某個值是0、正數還是負數,分別返回0、1、-1,

用如下的SQL語句取較小值:

select monthid,decode(sign(sale-6000),-1,sale,6000) from output;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM