【SQL】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;
 
3956112-23749d20e8746b2e.png
 

2、搜索表达式

select *,case when sex='1' then '男' when sex='2' then '女' end as sexdesc from score;
 
3956112-ff9d276366e416b5.png
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;
 
3956112-5d5c993c4b96781c.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
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 ;
 
3956112-a19dc5e78dc054ea.png
 

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;
 
3956112-696080a51a3ff67d.png
2019-07-06-175658.png

参考资料

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

  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值