【32】SQL Case When用法

简介

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;

2、搜索表达式

select *,case when sex='1' then '男' when sex='2' then '女' end as sexdesc from score;
2019-07-06-143912.png

相关用法

1、case whengroup 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;
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;
2019-07-06-161315.png

2、case whenorder by一起使用

//按不同的条件进行排序
select * from score order by case when sex=1 then score end desc,case when sex=2 then score end ;

3、case whenhaving一起使用

//显示出男生分数大于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;
2019-07-06-175658.png

参考资料

CASE (Transact-SQL)
CASE WHEN 及 SELECT CASE WHEN的用法

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容