Case表示式與decode()函式

skyin_1603發表於2016-10-09

Case表示式與decode()函式兩者都是根據欄位或者表示式作為判斷條件,當條件滿足
某個值或者範圍時,對應有一個結果。多個結果由多個互補相同的條件限制。所以這兩個的用法
很接近,大同小異,只是case的用法更靈活一些。

以下是透過例子講述一下:(根據不同的職位進行工資調整
檢視emp資訊:職位為SALESMAN,升工資為1.5倍,職位為MANAGER,升工資為2.0倍,職位為PRESIDENT,升工資為3.0倍,其他不升。

1、
decode:

decode(column|ecpression,search1,result1,

      [search2,result2,... ...]

      [,default] );

欄位或者表示式作為條件,當條件為search1,返回結果result1...當不滿足以上的條件,指定預設值為default

SQL> select ename,job,deptno,sal,

  2    decode(job,'PRESIDENT',3*sal,'MANAGER',2*sal,'SALESMAN',1.5*sal,sal) salary

  3  from emp

  4  order by deptno;

ENAME      JOB           DEPTNO        SAL     SALARY

---------- --------- ---------- ---------- ----------

CLARK      MANAGER           10       2450       4900

KING       PRESIDENT         10       5000      15000

MILLER     CLERK             10       1300       1300

JONES      MANAGER           20       2975       5950

FORD       ANALYST           20       3000       3000

ADAMS      CLERK             20       1100       1100

SMITH      CLERK             20        800        800

SCOTT      ANALYST           20       3000       3000

WARD       SALESMAN          30       1250       1875

TURNER     SALESMAN          30       1500       2250

ALLEN      SALESMAN          30       1600       2400


ENAME      JOB           DEPTNO        SAL     SALARY

---------- --------- ---------- ---------- ----------

JAMES      CLERK             30        950        950

BLAKE      MANAGER           30       2850       5700

MARTIN     SALESMAN          30       1250       1875

14 rows selected.




2、Case:(常搭配 when...then...)

SQL> select ename,job,deptno,sal,

  2  Case job

  3  when 'PRESIDENT'then 3*sal

  4  when 'MANAGER' then 2*sal

  5  when 'SALESMAN' then 1.5*sal

  6  else sal

  7  end salary

  8  from emp

  9  order by deptno;

ENAME      JOB           DEPTNO        SAL     SALARY

---------- --------- ---------- ---------- ----------

CLARK      MANAGER           10       2450       4900

KING       PRESIDENT         10       5000      15000

MILLER     CLERK             10       1300       1300

JONES      MANAGER           20       2975       5950

FORD       ANALYST           20       3000       3000

ADAMS      CLERK             20       1100       1100

SMITH      CLERK             20        800        800

SCOTT      ANALYST           20       3000       3000

WARD       SALESMAN          30       1250       1875

TURNER     SALESMAN          30       1500       2250

ALLEN      SALESMAN          30       1600       2400


ENAME      JOB           DEPTNO        SAL     SALARY

---------- --------- ---------- ---------- ----------

JAMES      CLERK             30        950        950

BLAKE      MANAGER           30       2850       5700

MARTIN     SALESMAN          30       1250       1875

14 rows selected.

以上查詢出來的結果是一樣的。

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/31392094/viewspace-2126003/,如需轉載,請註明出處,否則將追究法律責任。

相關文章