Oracle中decode函式和sign函式的用法
資料庫表結構如下:
流程控制函式 DECODE
decode()函式簡介:
主要作用:
將查詢結果翻譯成其他值(即以其他形式表現出來,以下舉例說明);
使用方法:
Select decode(columnname,值1,翻譯值1,值2,翻譯值2,…值n,翻譯值n,預設值)
From talbename
Where …
其中columnname為要選擇的table中所定義的column,
含義解釋:
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
注:其中預設值可以是你要選擇的column name 本身,也可以是你想定義的其他值,比如Other等;
舉例說明:
現定義一table名為output,其中定義兩個column分別為monthid(var型)和sale(number型),若sale值=1000時翻譯為D,=2000時翻譯為C,=3000時翻譯為B,=4000時翻譯為A,如是其他值則翻譯為Other;
SQL如下:
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()函式等;
比較大小函式 sign
函式語法:
sign(n)
函式說明:
取數字n的符號,大於0返回1,小於0返回-1,等於0返回0
示例:
1、select sign( 100 ),sign(- 100 ),sign( 0 ) from dual;
SIGN(100) SIGN(-100) SIGN(0)
———- ———- ———-
1 -1 0
2、a=10,b=20
則sign(a-b)返回-1
現在的需求是:在要用decode函式實現以下幾個功能:成績>85,顯示優秀;>70顯示良好;>60及格;否則是不及格。
select name, decode(sign(score-85),1,'優秀',0,'優秀',-1,
decode(sign(score-70),1,'良好',0,'良好',-1,
decode(sign(score-60),1,'及格',0,'及格',-1,'不及格')))
from test;
結果如下圖所示:
需要注意的是:mysql裡面是沒有decode函式的,如果需要實現上述效果,可以用case when函式來實現。
select name,score,(case when score >=85 then '優'
when score between 75 and 84 then '良'
when score between 60 and 74 then '及格'
when score <60 then '不及格'
when score is null then '缺考' end) 分數等級評價
from test;