SQL decode 函數的用法


decode 函數基本語法

decode(字段|表達式,條件1,結果1,條件2,結果2,...,條件n,結果n,缺省值);
--缺省值可以省略

 表示如果 字段|表達式 等於 條件1 時,DECODE函數的結果返回 條件1 ,...,如果不等於任何一個條件值,則返回缺省值
【注意】:decode 函數 ,只能在select 語句用。

decode 函數 用法

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

sql 測試:

1 select empno,
2        decode(empno,
3        7369,'smith',
4        7499,'allen',
5        7521,'ward',
6        7566,'jones',
7        'unknow') as name 
8 from emp 
9 where rownum<=10;

2.使用decode 函數比較大小

輸出兩個數中的較小值:

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

示例:

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

3.使用decode 函數分段

設 工資大於等於5000為高薪,大於等於3000且小於5000為中薪,低於3000為低薪 則每個人的工資水平是...?

 1 select e.ename ,e.sal,
 2        decode(sign(e.sal-5000),
 3        1, 'high sal',
 4        0, 'hign sal',
 5        -1,
 6           decode(sign(e.sal-3000),
 7           1, 'mid sal',
 8           0, 'mid sal',
 9           -1,'low sal'
10              )
11           )
12         as "工資等級" 
13 from scott.emp e;

(4,5還沒掌握)

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

1 select 
2    sum(decode(e.ename,upper('smith'),sal,0)) smith,
3    sum(decode(e.ename,upper('allen'),sal,0)) allen,
4    sum(decode(e.ename,upper('ward'),sal,0)) ward,
5    sum(decode(e.ename,upper('jones'),sal,0)) jones,
6    sum(decode(e.ename,upper('martin'),sal,0)) martin
7 from scott.emp e ;

sum 函數的用法 ?

5.使用decode函數來使用表達式來搜索字符串

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

1 select 
2    sum(decode(e.ename,upper('smith'),sal,0)) smith,
3    sum(decode(e.ename,upper('allen'),sal,0)) allen,
4    sum(decode(e.ename,upper('ward'),sal,0)) ward,
5    sum(decode(e.ename,upper('jones'),sal,0)) jones,
6    sum(decode(e.ename,upper('martin'),sal,0)) martin
7 from scott.emp e ;

 轉載自https://blog.csdn.net/weeknd/article/details/71157044


免責聲明!

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



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