一:簡單用法:sql
1.第一種寫法:函數
SELECT s.s_id, s.s_name, s.s_sex, CASE WHEN s.s_sex = '1' THEN '男' WHEN s.s_sex = '2' THEN '女' ELSE '其餘' END as sex, s.s_age, s.class_id FROM t_b_student s WHERE 1 = 1
2.第二種寫法spa
SELECT s.s_id, s.s_name, s.s_sex, CASE s.s_sex WHEN '1' THEN '男' WHEN '2' THEN '女' ELSE '其餘' END as sex, s.s_age, s.class_id FROM t_b_student s WHERE 1 = 1
兩個運行結果同樣:code
有一個須要注意的問題,Case函數只返回第一個符合條件的值,剩下的Case部分將會被自動忽略blog
二:分組io
表數據:class
t_b_population
sql語句:sql語句
SELECT country, SUM(CASE WHEN p.sex = '1' THEN p.population ELSE 0 END) AS '男', SUM(CASE WHEN p.sex = '2' THEN p.population ELSE 0 END) AS '女' FROM t_b_population p GROUP BY country;
運行結果:im
表數據:數據
t_b_country
sql語句:
SELECT SUM(c.population) AS '人口', CASE c.country WHEN '中國' THEN '亞洲' WHEN '印度' THEN '亞洲' WHEN '日本' THEN '亞洲' WHEN '美國' THEN '北美洲' WHEN '加拿大' THEN '北美洲' WHEN '墨西哥' THEN '北美洲' ELSE '其餘' END AS '洲' FROM t_b_country c GROUP BY CASE c.country WHEN '中國' THEN '亞洲' WHEN '印度' THEN '亞洲' WHEN '日本' THEN '亞洲' WHEN '美國' THEN '北美洲' WHEN '加拿大' THEN '北美洲' WHEN '墨西哥' THEN '北美洲' ELSE '其餘' END;
運行結果: