在使用SQL查询数据的时,很多情况下需要对数据的内容进行一定的转化,此时case..when..then..else..end就派上用场
下面对每个部分后面加的内容做一个简单的描述;
case:后面直接when
when:后面接的就是你所需要判断字段的值
then:后面接的就是新值(将when后面的接的数值变成then后面的数值)
else:后面一般接“其他”
end;
下面举个例子巩固一下:
1、创建一个test表
create table test(name varchar(20),type varchar(10),score varchar(10))
2、插入几条数据(总共插入9条数据)
insert into test values(‘张三’,‘1’,‘80’)
3、查看一下是否已经插入
select * from test
4、现在需要把type=1改为“语文”,type=2改为“数学”,type=3改为“英语”,剩余的设置为“其他”,NAME、SCORE不变。
select a.name,(case when a.type='1' then '语文' when a.type='2' then '数学' when a.type='3' then '英语' else '其他' end) as type,a.score from test a;
结果如下: