描述:根据某一字段的不同值,为另一字段取不同的别名。
背景:建一个学生缺勤表,其中有一个字段是缺勤状态status,取值为0-5,分别代表旷课、早到、迟到、病假、事假、公假。求出各系 各缺勤状态的人数。
`
select 系别,
sum(case when 缺勤状态=0 then 1 else 0 end) as 旷课人数,
sum(case when 缺勤状态=1 then 1 else 0 end) as 早退人数,
sum(case when 缺勤状态=2 then 1 else 0 end) as 迟到人数,
sum(case when 缺勤状态=3 then 1 else 0 end) as 病假人数,
sum(case when 缺勤状态=4 then 1 else 0 end) as 事假人数,
sum(case when 缺勤状态=5 then 1 else 0 end) as 公假人数
from 学生缺勤表
group by 系别
使用 case when
即可为 某一字段取不同别名。