【32】SQL Case When用法
2019-07-06 本文已影响7人
业余玩家
简介
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;

相关用法
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;

//统计各科目的考试男生人数和女生人数。
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;

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
一起使用
//显示出男生分数大于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;
