case when的基本使用:
Case when 的用法: 一旦满足了某一个WHEN, 则这一条数据就会退出CASE WHEN , 而不再考虑 其他CASE。
Case when 的用法
-- -搜索Case函数:
Case函数(Case搜索函数): 判断表达式的真假,如果为真,返回结果;如果为假,返回else值;如果未定义else值,则返回空值(使用条件确定返回值);
select name,id,(case when id=34 then salary*2
when id=45 then salary*3
else salary
end) new_salary
from semp;
-- -简单Case函数
简单Case表达式的作用是: 使用表达式确定返回值:
select id,name,(case sex
when '1' then '男'
when '2' then '女'
else '其他' end)
from student;
这两种方法可以实现相同的功能. 简单Case函数的写法比较简单,但是和case搜索函数相比,功能方面会有些限制,比如判断式。
还有一个需要注意的问题,Case函数只返回第一个符合条件的值,剩下的Case部分将会被自动忽略。
比如下面 SQL,将无法得到第二个结果:(差永远获取不到)。
sql如下
case when colum in ('a', 'b') then '优秀'
when colum in ('a') then '差'
else '其他' end
case when的使用场景有三种:
- 等值转换
- 范围转换
- 列转行操作
1.等值转换
设计数据库的时候总会把用户的性别用int存储('0’为女,'1’为男),但是怎么把它抓换成汉字显示呢?
-
select name as '姓名',
-
(case sex when 0 then '女' else '男' end) as '性别'
-
from test.student;
查询结果:
2.范围转换
按照用户成绩显示优(90分以上)、良(80分-90分)、及格(60分-80分)、不及格(60分一下):
sql语句:
-
select name as '姓名',
-
(case when score > 90 then '优' when score >= 80 then '良' when score >= 60 then '及格' else '不及格' end) as '等级'
-
from test.stu_score;
运行结果:
3.列转行操作
表一
-
+----------+---------+------+
-
| class_id | grade | rate |
-
+----------+---------+------+
-
| abc123 | primary | 70% |
-
| abc123 | middle | 65% |
-
| abc123 | high | 72% |
-
| hjkk86 | primary | 69% |
-
| hjkk86 | middle | 63% |
-
| hjkk86 | high | 74% |
-
+----------+---------+------+
表二
-
+----------+---------+--------+------+
-
| class_id | primary | middle | high |
-
+----------+---------+--------+------+
-
| abc123 | 70% | 65% | 72% |
-
| hjkk86 | 69% | 63% | 74% |
-
+----------+---------+--------+------+
将表一转换成表二显示:
第一步 其中三条CASE WHEN 语句是同步执行的
-
select class_id,
-
(case when grade = 'primary' then rate else 0 end) as 'primary',
-
(case when grade = 'middle' then rate else 0 end) as 'middle',
-
(case when grade = 'high' then rate else 0 end) as 'high'
-
from mst_class;
-
+----------+---------+--------+------+
-
| class_id | primary | middle | high |
-
+----------+---------+--------+------+
-
| abc123 | 70% | 0 | 0 |
-
| abc123 | 0 | 65% | 0 |
-
| abc123 | 0 | 0 | 72% |
-
| hjkk86 | 69% | 0 | 0 |
-
| hjkk86 | 0 | 63% | 0 |
-
| hjkk86 | 0 | 0 | 74% |
-
+----------+---------+--------+------+
第二步 按class_id分组,求最大值(即去掉0)
-
select class_id,
-
max(case when grade = 'primary' then rate else 0 end) as 'primary',
-
max(case when grade = 'middle' then rate else 0 end) as 'middle',
-
max(case when grade = 'high' then rate else 0 end) as 'high'
-
from mst_class
-
group by class_id;
-
+----------+---------+--------+------+
-
| class_id | primary | middle | high |
-
+----------+---------+--------+------+
-
| abc123 | 70% | 65% | 72% |
-
| hjkk86 | 69% | 63% | 74% |