描述:根據某一字段的不同值,爲另一字段取不同的別名。
背景:建一個學生缺勤表,其中有一個字段是缺勤狀態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
即可爲 某一字段取不同別名。