格式:
case expression
when condition_01 then result_01
when condition_02 then result_02
......
when condition_n then result_n
else result_default
end
表达式expression符合条件condition_01,则返回结果result_01,若该条件不满足,则继续往下判断;以此类推,若不满足上一个条件,则继续判断是否满足下一个条件
若以上条件都不满足,则返回默认值result_default,若省略默认值result_default,则返回null
示例
create table T_STUDENT_SCORE
(
studentid VARCHAR2(30) not null,
classid VARCHAR2(30),
score NUMBER,
scorelevel VARCHAR2(30)
)
insert into T_STUDENT_SCORE (studentid, classid, score, scorelevel) values ('StudId01', 'ClasId01', 50, 'E');
insert into T_STUDENT_SCORE (studentid, classid, score, scorelevel) values ('StudId02', 'ClasId01', 60, 'D');
insert into T_STUDENT_SCORE (studentid, classid, score, scorelevel) values ('StudId03', 'ClasId01', 70, 'C');
insert into T_STUDENT_SCORE (studentid, classid, score, scorelevel) values ('StudId04', 'ClasId02', 80, 'B');
insert into T_STUDENT_SCORE (studentid, classid, score, scorelevel) values ('StudId05', 'ClasId02', 90, 'A');
insert into T_STUDENT_SCORE (studentid, classid, score, scorelevel) values ('StudId06', 'ClasId02', 100, 'S');
最后查询表中数据,返回结果如下
【样例展示1】
sql语句如下:
select t.*,case score when 100 then '完美' end as fullScoreFlag from T_STUDENT_SCORE t
返回结果如下图:若是100分,则返回“完美”,否则返回null
【样例展示2】
sql语句如下:
select t.*,case score when 100 then '完美' else '其他' end as fullScoreFlag from T_STUDENT_SCORE t
返回结果如下图:若是100分,则返回“完美”,否则返回“其他”
【样例展示3】
sql语句如下:
select t.*,case score when 100 then '完美' when 90 then '优秀' end as fullScoreFlag from T_STUDENT_SCORE t
返回结果如下图:若是100分,则返回“完美”,若是90分,则返回“优秀”,否则返回null
【样例展示4】
sql语句如下:
select t.*,case score when 100 then '完美' when 90 then '优秀' else '其他' end as fullScoreFlag from T_STUDENT_SCORE t
返回结果如下图:若是100分,则返回“完美”,若是90分,则返回“优秀”,否则返回“其他”
【样例展示5】
sql语句如下:
select * from T_STUDENT_SCORE
order by
case
when scoreLevel='S' then 0
when scoreLevel='A' then 1
when scoreLevel='B' then 2
when scoreLevel='C' then 3
when scoreLevel='D' then 4
else 5 end
asc
返回结果如下图:按成绩评级由高到低排序。
【样例展示6】
sql语句如下:
select
count(*),
case
when scoreLevel='S' then '不错'
when scoreLevel='A' then '不错'
when scoreLevel='B' then '一般'
when scoreLevel='C' then '一般'
when scoreLevel='D' then '较差'
when scoreLevel='E' then '较差'
else '其他' end as scoreRemark
from T_STUDENT_SCORE
group by
case
when scoreLevel='S' then '不错'
when scoreLevel='A' then '不错'
when scoreLevel='B' then '一般'
when scoreLevel='C' then '一般'
when scoreLevel='D' then '较差'
when scoreLevel='E' then '较差'
else '其他' end
返回结果如下图:按成绩评级分组统计学生数量
【样例展示7】
sql语句如下:
select * from T_STUDENT_SCORE where
(case
when scoreLevel='S' then '不错'
when scoreLevel='A' then '不错'
when scoreLevel='B' then '一般'
when scoreLevel='C' then '一般'
when scoreLevel='D' then '较差'
when scoreLevel='E' then '较差'
else '其他' end)='不错'
返回结果如下图:按成绩评级作为条件筛选成绩不错的学生