热线电话:13121318867

登录
2020-12-23 阅读量: 900
mysql中 case when所有使用场景

等值转换

用户的性别用int存储('0'为女,'1'为男),但是怎么把它转换成汉字显示


SQL语句

select

name as '名字',

(case sex when 0 then '女' else '男' end) as '性别'

from test.student;


范围转换

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

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显示出来呢?


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

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;


0.0000
0
关注作者
收藏
评论(0)

发表评论

暂无数据