一文搞懂case when所有使用场景

前几天,为了给产品分析当前用户数据结构,写sql的时候使用到了case when,今天来总结一下case when 的使用方法,以此为戒,感觉写的不好请拍砖,感觉写的还可以,给哥们点个赞,或者回复一下,让我意识到我不是一个人在战斗,好了废话不多说了,进入正题。

关于case when的使用情况,我总结下来有三种,第一、等值转换,第二、范围转换,第三、列转行操作。

等值转换

咱们在设计数据库的时候总是会把用户的性别用int存储('0'为女,'1'为男),但是怎么把它转换成汉字显示呢?

原始表数据

SQL语句

select
name as '名字',
(case sex when 0 then '女' else '男' end) as '性别'
from test.student;

ps.最后的 'end' 别丢了,我刚开始使用的时候我就有这个毛病,并且一般的case when语句都会比较长,最好添加小括号包起来,这样更容易阅读。

查询结果

范围转换

有的时候,也会遇到这种情况,按照用户成绩显示优(90+)、良(80-90)、及格(60-80)、未及格(60-),这个跟第一个不同的是,他是一个分数的范围,要怎么转换成汉子显示呢?你可能觉得很简单,不就是吧when那换成条件吗?先打住咱们往下看

原始表数据

SQL语句

select 
name as '姓名'
,(case score when score>=90 then '优' when score>=80 then '良' when score>=60 then '及格' else '不及格' end) as '等级'
from test.stu_score; 

这样写对不?

这个查出来的结果是

这是为啥呢?想明白了吗? 

因为 case when就像一个 switch case语句一样,如果你在case后填了东西,它会拿后它跟when 对比,咱们的 写的case 后写=了 score 而when后面写了score>=90 ,然而,'score' 等于 'score>=90'吗? 显然不等于,那该怎么写呢?

select 
name as '姓名'
,(case score when score>=90 then '优' when score>=80 then '良' when score>=60 then '及格' else '不及格' end) as '等级'
from test.stu_score; 

列转行操作

还是用学生的例子吧,现在有图1学生成绩数据, 现在要怎么按图2显示出来呢?

图1

图2

第一步 先按照科目分开, 符合条件的设置分数,不符合的给置零。

select name as '姓名'
,(case course when '语文' then score else 0 end) as '语文'
,(case course when '数学' then score else 0 end) as '数学'
,(case course when '英语' then score else 0 end) as '英语'
from test.course_score

然后再按照名字group by ,对分数求max。

select name as '姓名'
,max(case course when '语文' then score else 0 end) as '语文'
,max(case course when '数学' then score else 0 end) as '数学'
,max(case course when '英语' then score else 0 end) as '英语'
from test.course_score group by name;

 
————————————————
版权声明:本文为CSDN博主「慕容田雨」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/changxiangyangy/article/details/86718551

猜你喜欢

转载自www.cnblogs.com/diyhlgc/p/12711628.html