我有一个名为出勤的表,有2个属性(id,备注)。我想从出勤表中显示缺席或迟到的每个身份证。
Attendance Table
|ID | Remarks |
=============================
|1 | Absent |
|1 | Late |
|2 | Absent |
|2 | Absent |
|3 | Late |
Sample Output
|ID | Absent | Late |
==================================
|1 | 1 | 1 |
|2 | 2 | |
|3 | | 1 |
目前,我只能使用以下代码输出2列(ID和Absent)或(ID和Late):
SELECT id, count(remarks) AS Absent
FROM attendance
WHERE remarks = 'Absent'
GROUP BY id;
我不能同时显示缺席和晚期列..请帮忙。感谢。
答案 0 :(得分:2)
这基本上是PIVOT
。如果您无法访问PIVOT
函数,则可以使用聚合函数和CASE
语句复制它:
select id,
sum(case when remarks = 'Absent' then 1 else 0 end) Absent,
sum(case when remarks = 'Late' then 1 else 0 end) Late
from attendance
group by id
或者您可以使用COUNT()
:
select id,
count(case when remarks = 'Absent' then 1 else null end) Absent,
count(case when remarks = 'Late' then 1 else null end) Late
from attendance
group by id;
答案 1 :(得分:0)
使用SUM(CASE)
构造分隔Absent
和Late
。对于每一个,如果值匹配,则CASE返回1或0,然后通过汇总SUM()
将这些值相加,得出总数。这里的概念被称为pivot table。
SELECT
id,
SUM(CASE WHEN Remarks = 'Absent' THEN 1 ELSE 0 END) AS Absent,
SUM(CASE WHEN Remarks = 'Late' THEN 1 ELSE 0 END) AS Late
FROM
attendance
GROUP BY id
答案 2 :(得分:0)
尝试:
SELECT id,
Sum (Case remarks When 'Absent' Then 1 End) Absent,
Sum (Case remarks When 'Late' Then 1 End) Late
FROM attendance
GROUP BY id;