SQL之case when then用法詳解


case具有兩種格式。簡單case函數和case搜索函數。

1 --簡單case函數  2 case sex 3 when '1' then '' 4 when '2' then '女’ 5  else '其他' end 6 --case搜索函數 7 case when sex = '1' then '' 8  when sex = '2' then '' 9  else '其他' end

這兩種方式,可以實現相同的功能。簡單case函數的寫法相對比較簡潔,但是和case搜索函數相比,功能方面會有些限制,比如寫判定式。

還有一個需要注重的問題,case函數只返回第一個符合條件的值,剩下的case部分將會被自動忽略。

 

實例演示:
首先創建一張users表,其中包含id,name,sex三個字段,表內容如下:

ID        NAME                 SEX
---------- -------------------- ----------
1          張一                 
2          張二                 1
3          張三                 
4          張四                
5          張五                 2
6          張六                 1
7          張七                 2
8          張八                 1

1、上表結果中的"sex"是用代碼表示的,希望將代碼用中文表示。可在語句中使用case語句:
1 select u.id,u.name,u.sex, 2   (case u.sex 3    when 1 then ''  
4    when 2 then ''  
5    else '空的'  
6    end  
7    )性別 8 from users u;
ID NAME                        SEX 性別
--------------------------------------- 
1 張一                              空的
2 張二                          1   男
3 張三                              空的
4 張四                              空的
5 張五                          2   女
6 張六                          1   男
7 張七                          2   女
8 張八                          1   男

 

2. 將sum與case結合使用,可以實現分段統計。
    如果現在希望將上表中各種性別的人數進行統計,sql語句如下:

 1 select
 2   sum(case u.sex when 1 then 1 else 0 end) 男性,  3   sum(case u.sex when 2 then 1 else 0 end) 女性,  4   sum(case when u.sex <>1 and u.sex<>2 then 1 else 0 end)性別為空  5 from users u;  6  
 7  男性 女性 性別為空  8 ---------- ---------- ----------
 9          3        2          0
10 
11 --------------------------------------------------------------------------------
12 select
13   count(case when u.sex=1 then 1 end)男性, 14   count(case when u.sex=2 then 1 end)女, 15   count(case when u.sex <>1 and u.sex<>2 then 1 end)性別為空 16 from users u; 17  
18  男性 女 性別為空 19 ---------- ---------- ----------
20        3          2          0

 


免責聲明!

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



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