簡介
case when sql中計算條件列表,并返回多個可能的結果表達式之一。
CASE 表達式有兩種格式:1、CASE 簡單表達式,它通過將表達式與一組簡單的表達式進行比較來確定結果。2、CASE 搜索表達式,它通過計算一組布爾表達式來確定結果。這兩種格式都支持可選的 ELSE 參數(shù)。
可以在 SELECT、UPDATE、DELETE 和 SET 等語句以及 select_list、IN、WHERE、ORDER BY 和 HAVING 等子句中使用 CASE。這里使用MySQL數(shù)據(jù)庫進行操作。
語法格式
1、簡單表達式
select *,case sex when '1' then '男' when '2' then '女' else '其他' end as sexdesc from score;

2、搜索表達式
select *,case when sex='1' then '男' when sex='2' then '女' end as sexdesc from score;

2019-07-06-143912.png
相關用法
1、case when和group by一起使用
//統(tǒng)計各分段內的學生數(shù)
select count(*) as nums,case when score<90 then '小于90分' else '不小于90分' end as status from score group by y case when score<90 then '小于90分' else '不小于90分' end;

2019-07-06-160504.png
//統(tǒng)計各科目的考試男生人數(shù)和女生人數(shù)。
select course,count(case when sex=1 then 1 else null end) as '男生數(shù)',count(case when sex=2 then 1 else null end) as '女生數(shù)' from score group by course;

2019-07-06-161315.png
2、case when和order by一起使用
//按不同的條件進行排序
select * from score order by case when sex=1 then score end desc,case when sex=2 then score end ;

3、case when和having一起使用
//顯示出男生分數(shù)大于85,女生分數(shù)大于80的學生。
select * from score having (case when sex=2 then score else null end)>80 or (case when sex=1 then score else null end)>85;

2019-07-06-175658.png