CASE關鍵字有兩種使用方法,分別是‘簡單case函數’和‘case搜索函數’
簡單case函數
CASE sex WHEN '1' THEN '男' WHEN '2' THEN '女' ELSE '其他' END
case搜索函數
CASE WHEN sex='1' THEN '男' WHEN sex='2' THEN '女' ELSE '其他' END
分析說明
- 簡單case函數是case搜索函數的真子集
- 簡單case函數的使用方法與一些高級語言(如:java)中的switch語句相似:CASE給定匹配字段,WHEN給出具體的字段值,如果匹配到后返回THEN值。
- 簡單case函數其實就是case搜索函數的‘=’邏輯的實現。case搜索函數可以實現簡單case函數的所有功能,而簡單case函數卻不可實現case搜索函數的‘=’邏輯以外的功能。
- case函數匹配原則
- case函數與switch的不同在於case僅返回第一個匹配到的結果,而switch則會在沒有中斷的情況下繼續后面的判斷,將會執行所有匹配的結果。
- case搜索函數比簡單case函數更加靈活
- case搜索函數與簡單case函數相比的靈活之處在於可以在WHEN中書寫判斷式。
1、等值轉換
SELECT user_name,( CASE WHEN sex = 0 THEN '男人' WHEN sex = 1 THEN '女人' ELSE '中性人' END ) AS 性別 FROM imooc_goddess;
SELECT user_name,( CASE sex WHEN 0 THEN '男人' WHEN 1 THEN '女人' ELSE null END ) AS 性別 FROM imooc_goddess;
2、范圍轉換
select user_name, (case when age BETWEEN 0 and 18 then '未成年' when age BETWEEN 18 and 30 then '成年' when age BETWEEN 30 and 50 then '中年人' else '老年人' end) as 年齡段
FROM imooc_goddess;
select user_name,(case when age>0 and age<=18 then '未成年' when age >18 and age<=30 then '成年' when age >30 and age<=50 then '中年人' else '老年人' end) as 年齡段 FROM imooc_goddess;
3、行轉列
select name , (case when sub = 'english' then score else 0 end ) 'english' ,
(case when sub = 'maths' then score else 0 end) 'maths' ,
(case when sub = 'chinese' then score else 0 end) 'chinese'
FROM stu;
select name , sum((case when sub = 'english' then score else 0 end )) 'english' ,
sum((case when sub = 'maths' then score else 0 end)) 'maths' ,
sum((case when sub = 'chinese' then score else 0 end)) 'chinese'
FROM stu GROUP BY name ;
1.IF
表達式:IF( expr1 , expr2 , expr3 )
expr1條件,條件為true,則值是expr2 ,false,值就是expr3
2. IFNULL
表達式:IFNULL( expr1 , expr2)
在 expr1 的值不為 NULL的情況下都返回 expr1,否則返回 expr2