case when的使用情况一般有三种:等值转换、范围转换、列转行操作
一、 等值转换
在数据库中建表的时候总是会把用户的性别存储为int类型('0’为女,'1’为男),但是如何转换成汉字显示呢?
原始表数据:
-- a1
drop table if exists a1;
create table a1(
id bigint default '0' not null comment '主键id',
name char(100) default '' not null comment '姓名',
sex int default '0' not null
);
insert into a1 values (1,'张三',0);
insert into a1 values (2,'李四',1);
insert into a1 values (3,'王五',1);
insert into a1 values (3,'赵六',0);
转换后结果:
select
id,
name ,
(case sex
when 0 then '女'
else '男' end) as sex
from a1;
或者
select
id,
name ,
(case
when sex=0 then '女'
else '男' end) as sex
from a1;
一般的case when语句都会比较长,最好添加小括号包起来,这样更容易阅读。
二、范围转换
有时会遇到这种情况,按照用户成绩显示优(90+)、良(80-90)、及格(60-80)、未及格(60-),这是一个分数的范围,要如何转换成汉字显示呢?
原始表数据:
-- a2
drop table if exists a2;
create table a2(
id bigint default '0' not null comment '主键id',
name char(100) default '0' not null comment '名字',
score int default '0' not null comment '分数'
);
insert into a2 values (1,'张三',67);
insert into a2 values (2,'李四',83);
insert into a2 values (3,'王五',55);
insert into a2 values (3,'赵六',92);
转换后结果:
select
id,
name ,
(case
when score>=90 then '优'
when score>=80 then '良'
when score>=60 then '及格'
else '不及格' end) as level
from a2;
注:此时,case后面不可以跟任何东西,因为case when就像一个switch case语句,如果在case后跟了东西,它会拿它跟when对比;如果case后写了=score,而when后面写了score>=90 ,而'score'等于'score>=90'吗? 显然不等于。
三、列转行操作
现在有原始表“学生成绩表”, 要如何按照图2显示出来呢?
原始表数据:
-- a3
drop table if exists a3;
create table a3(
id bigint default '0' not null comment '主键id',
name char(100) default '0' not null comment '名字',
course char(100) default '0' not null comment '课程',
score int default '0' not null comment '分数'
);
insert into a3 values (1,'张三','数学',98);
insert into a3 values (2,'张三','语文',89);
insert into a3 values (3,'张三','英语',77);
insert into a3 values (4,'李四','数学',79);
insert into a3 values (5,'李四','语文',86);
insert into a3 values (6,'李四','英语',92);
转换后结果:
1、首先按照科目分开,符合条件的设置分数,不符合的给置零。
select
name,
(case when course='语文' then score else 0 end) as '语文',
(case when course='数学' then score else 0 end) as '数学',
(case when course='英语' then score else 0 end) as '英语'
from a3
2、然后按照名字group by,对分数求max
select
name,
max(case when course='语文' then score else 0 end) as '语文',
max(case when course='数学' then score else 0 end) as '数学',
max(case when course='英语' then score else 0 end) as '英语'
from a3
group by name;
总结
以上就是今天要讲的内容,本文主要介绍了目前遇到的case when所有使用场景,包括:等值转换、范围转换、列转行操作,后续若遇到其他场景会继续更新。