4

我有一个名为出席的表,有 2 个属性(id、备注)。我想从考勤表中显示每个 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;

我不能同时显示缺席和迟到的列..请帮忙。谢谢。

4

3 回答 3

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

请参阅带有演示的 SQL Fiddle

或者您可以使用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;

请参阅带有演示的 SQL Fiddle

于 2012-11-15T16:28:12.833 回答
0

使用SUM(CASE)构造来分隔AbsentLate。对于每一个,如果值匹配,则 CASE 返回 1 或 0,然后通过聚合SUM()得到总数。这里起作用的概念称为数据透视表

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
于 2012-11-15T16:28:12.333 回答
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;
于 2012-11-15T16:28:30.147 回答