1. CASE WHEN 表達式有兩種形式

 

複製代碼

--簡單Case函數  

CASE sex  
WHEN '1' THEN '男'  
WHEN '2' THEN '女'  
ELSE '其餘' END  

--Case搜索函數  

CASE
WHEN sex = '1' THEN '男'  
WHEN sex = '2' THEN '女'  
ELSE '其餘' END

複製代碼

 

2. CASE WHEN 在語句中不一樣位置的用法

2.1 SELECT CASE WHEN 用法

複製代碼

SELECT   grade, COUNT (CASE WHEN sex = 1 THEN 1      /*sex 1爲男生,2位女生*/
                       ELSE NULL
                       END) 男生數,
                COUNT (CASE WHEN sex = 2 THEN 1
                       ELSE NULL
                       END) 女生數
    FROM students GROUP BY grade;

複製代碼

 

2.3 WHERE CASE WHEN 用法

複製代碼

SELECT T2.*, T1.*
   FROM T1, T2
  WHERE (CASE WHEN T2.COMPARE_TYPE = 'A' AND
                   T1.SOME_TYPE LIKE 'NOTHING%'
                THEN 1
              WHEN T2.COMPARE_TYPE != 'A' AND
                   T1.SOME_TYPE NOT LIKE 'NOTHING%'
                THEN 1
              ELSE 0
           END) = 1

複製代碼

 

2.4 GROUP BY CASE WHEN 用法

複製代碼

SELECT  
CASE WHEN salary <= 500 THEN '1'  
WHEN salary > 500 AND salary <= 600  THEN '2'  
WHEN salary > 600 AND salary <= 800  THEN '3'  
WHEN salary > 800 AND salary <= 1000 THEN '4'  
ELSE NULL END salary_class, -- 別名命名
COUNT(*)  
FROM    Table_A  
GROUP BY  
CASE WHEN salary <= 500 THEN '1'  
WHEN salary > 500 AND salary <= 600  THEN '2'  
WHEN salary > 600 AND salary <= 800  THEN '3'  
WHEN salary > 800 AND salary <= 1000 THEN '4'  
ELSE NULL END;

複製代碼

 

3.關於IF-THEN-ELSE的其餘實現

3.1 DECODE() 函數

select decode(sex, 'M', 'Male', 'F', 'Female', 'Unknown')
from   employees;

貌似只有Oracle提供該函數,並且不支持ANSI SQL,語法上也沒CASE WHEN清晰,我的不推薦使用。
 函數

3.2 在WHERE中特殊實現

SELECT T2.*, T1.*
   FROM T1, T2
  WHERE (T2.COMPARE_TYPE = 'A' AND T1.SOME_TYPE LIKE 'NOTHING%')
         OR
        (T2.COMPARE_TYPE != 'A' AND T1.SOME_TYPE NOT LIKE 'NOTHING%')

這種方法也是在特殊狀況下使用,要多注意邏輯,不要弄錯。spa

相關文章
相關標籤/搜索