(六)CASE WHEN 语句
1.语句
case when 条件 then 结果
[when .. then ..]
else 结果
end
如果省略了ELSE子句,则返回NULL
2.应用场景
(1)场景1:当分数大于60分时视为及格,其他情况视为不及格
select score.*
,case when score>60 then '及格' else '不及格' end pj
from score
case when score= 'A' THEN '优' ELSE 0 END
‘优’和0数据类型不一致则报错:
[Err] ORA-00932: 数据类型不一致: 应为 CHAR, 但却获得 NUMBER
这是因为THEN后边的值与ELSE后边的值类型应一致,否则会报错
(2)场景2:查询不各科及格与不及格的人数
select cid
,count(case when score>60 then '及格' end) pj_high
,count(case when score<60 then '不及格' end) pj_low
,sum(case when score>60 then THEN 1 end) pj_high2
,sum(case when score<60 then THEN 1 end) pj_low2
from score
group by cid
(3)场景3:要求查询不同科目的成绩情况,结果按照学号,01,02,03的字段顺序显示
select sid
,max(case when cid=01 then score end ) "01"
,max(case when cid=02 then score end ) "02"
,max(case when cid=03 then score end ) "03"
from score
group by sid
order by sid
作者:郭佳豪 创建时间:2023-10-18 09:53
最后编辑:郭佳豪 更新时间:2023-10-18 17:33
最后编辑:郭佳豪 更新时间:2023-10-18 17:33