oracle 中decode函式的用法

2021-08-25 13:53:43 字數 3012 閱讀 8865

1:使用decode判斷字串是否一樣

decode(value,if1,then1,if2,then2,if3,then3,...,else)

含義為if 條件=值1 then

return(value 1)

elsif 條件=值2 then

return(value 2)

......

elsif 條件=值n then

return(value 3)

else

return(default)

end if

sql測試

select empno,decode(empno,7369,'smith',7499,'allen',7521,'ward',7566,'jones','unknow') as name from emp where rownum<=10

輸出結果

7369 smith

7499 allen

7521 ward

7566 jones

7654 unknow

7698 unknow

7782 unknow

7788 unknow

7839 unknow

7844 unknow

2:使用decode比較大小

select decode(sign(var1-var2),-1,var 1,var2) from dual

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

sql測試

select decode(sign(100-90),-1,100,90) from dual

輸出結果

90100-90=10>0 則會返回1,所以decode函式最終取值為90

反正select decode(sign(100-90),1,100,90) from dual

輸出結果

100100-90=10>0返回1,判斷結果為1,返回第乙個變數100,最終輸出結果為100

3:使用decode函式分段

工資大於5000為高薪,工資介於3000到5000為中等,工資小於3000為低薪

sql測試

select 

ename,sal,

decode(sign(sal - 5000),

1,'high sal',

0,'high sal',

- 1,

decode(sign(sal - 3000),

1,'mid sal',

0,'mid sal',

- 1,

decode(sign(sal - 1000),

1,'low sal',

0,'low sal',

- 1,

'low sal')))

from

emp輸出結果

smith   800   low sal

allen 1600 low sal

ward 1250 low sal

jones 2975 low sal

martin 1250 low sal

blake   2850 low sal

clark 2450 low sal

scott 3000 mid sal

king  5000 high sal

turner 1500 low sal

adams 1100 low sal

james 950         low sal

ford 3000 mid sal

miller 1300 low sal

4:利用decode實現表或者試圖的行列轉換

sql測試

select 

sum(decode(ename,'smith',sal,0))  smith,

sum(decode(ename,'allen',sal,0))  allen,

sum(decode(ename,'ward',sal,0))   ward,

sum(decode(ename,'jones',sal,0))  jones,

sum(decode(ename,'martin',sal,0)) martin from emp

輸出結果如下

smith  allen  ward   jones  martin

800  1600   1250       2975       1250

5:使用decode函式來使用表示式來搜尋字串

decode (expression, search_1, result_1, search_2, result_2, ...., search_n, result_n, default)

decode函式比較表示式和搜尋字,如果匹配,返回結果;如果不匹配,返回default值;如果未定義default值,則返回空值。

sql測試

select 

ename,

sal,

decode(instr(ename, 's'),

0,'不含有s',

'含有s') as info

from

emp輸出結果

smith 800           含有s

allen 1600   不含有s

ward 1250   不含有s

jones 2975    含有s

martin 1250    不含有s

blake 2850    不含有s

clark 2450    不含有s

scott 3000   含有s

king 5000   不含有s

turner 1500   不含有s

adams 1100   含有s

james 950            含有s

ford 3000   不含有s

miller 1300   不含有s

Oracle 中 decode 函式用法

含 釋 decode 條件,值1,返回值1,值2,返回值2,值n,返回值n,預設值 該函式的含義如下 if 條件 值1 then return 翻譯值1 elsif 條件 值2 then return 翻譯值2 elsif 條件 值n then return 翻譯值n else return 預設值...

Oracle 中 decode 函式用法

含 釋 decode 條件,值1,返回值1,值2,返回值2,值n,返回值n,預設值 該函式的含義如下 if 條件 值1 then return 翻譯值1 elsif 條件 值2 then return 翻譯值2 elsif 條件 值n then return 翻譯值n else return 預設值...

Oracle 中 decode 函式用法

含 釋 decode 條件,值1,返回值1,值2,返回值2,值n,返回值n,預設值 該函式的含義如下 if 條件 值1 then return 翻譯值1 elsif 條件 值2 then return 翻譯值2 elsif 條件 值n then return 翻譯值n else return 預設值...