Oracle中decode函數的使用
decode 的幾種用法
1.使用decode判斷字符串是否一樣
DECODE(value,if 條件1,then 值1,if 條件2,then 值2,...,else 其他值)
Sql測試:
select aac001,decode(aac001,'0000000001','林海燕','0000000002','陳德財','others') as name from ac01 where rownum<=5;
輸出結果:
- 使用decode判比較大小
Select decode(sign(var1-var2),1,var1,var2) from dual
Sign()函數根據某個值是0、正數、負數,分別返回0、1、-1;
Sql測試:
Select decode(sign(100-90),1,100,90) from dual
輸出結果 :100
100-90=10>0則sign()返回1,decode()函數取值var1=100
Select decode(sign(100-90),-1,100,90) from dual
輸出結果:90
100-90=10>0則sign()返回1,decode()函數取值var2=100
- 使用decode函數分段
工資大於10000為高薪,工資介於5000到10000為中等,工資小於5000位低薪
Sql測試:
SELECT
ename,sal,
DECODE(SIGN(sal-10000),1,’高薪’,0,’高薪’,
-1,DECODE(SIGN(sal-5000),1’中等’,0,’中等’,
-1,’低薪’))) from ac01
輸出結果:
李明 12000 高薪
張三 5000 中等
王五 3000 低薪