简介
case when sql中计算条件列表,并返回多个可能的结果表达式之一。
CASE 表达式有两种格式:1、CASE 简单表达式,它通过将表达式与一组简单的表达式进行比较来确定结果。2、CASE 搜索表达式,它通过计算一组布尔表达式来确定结果。这两种格式都支持可选的 ELSE 参数。
可以在 SELECT、UPDATE、DELETE 和 SET 等语句以及 select_list、IN、WHERE、ORDER BY 和 HAVING 等子句中使用 CASE。这里使用MySQL数据库进行操作。
语法格式
1、简单表达式
select *,case sex when '1' then '男' when '2' then '女' else '其他' end as sexdesc from score;
![3956112-23749d20e8746b2e.png](https://i-blog.csdnimg.cn/blog_migrate/699b120186783732e0005051762c48e8.png)
2、搜索表达式
select *,case when sex='1' then '男' when sex='2' then '女' end as sexdesc from score;
![3956112-ff9d276366e416b5.png](https://i-blog.csdnimg.cn/blog_migrate/e6c56740c65b779415da8ec445669947.png)
2019-07-06-143912.png
相关用法
1、case when
和group by
一起使用
//统计各分段内的学生数
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;
![3956112-5d5c993c4b96781c.png](https://i-blog.csdnimg.cn/blog_migrate/021e611f08f41b4f45acda591089698a.png)
2019-07-06-160504.png
//统计各科目的考试男生人数和女生人数。
select course,count(case when sex=1 then 1 else null end) as '男生数',count(case when sex=2 then 1 else null end) as '女生数' from score group by course;
![3956112-680dbd11737cf34f.png](https://i-blog.csdnimg.cn/blog_migrate/fd73e058f14b80f3b65c6e2f82f1b30f.png)
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 ;
![3956112-a19dc5e78dc054ea.png](https://i-blog.csdnimg.cn/blog_migrate/a833718edd3b6d29ea8f4a36c911e613.png)
3、case when
和having
一起使用
//显示出男生分数大于85,女生分数大于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;
![3956112-696080a51a3ff67d.png](https://i-blog.csdnimg.cn/blog_migrate/bc7bb145382b1b0729cace934af2296e.png)
2019-07-06-175658.png