SQL PIVOT组由2列组成

时间:2016-10-14 02:04:23

标签: sql stored-procedures pivot-table

我有一个出勤表,如下所示我希望按时间和部分对它们进行分组,状态为 null 表示员工缺席:

enter image description here

知道如何生成如下输出吗?

enter image description here

我目前的代码:

SELECT TIME,COUNT(SECTION) AS SECTION,COUNT(STATUS) AS COUNT 
FROM attendance_record
GROUP BY TIME,SECTION
ORDER BY TIME

1 个答案:

答案 0 :(得分:2)

如果我理解你的问题,只需使用条件聚合:

SELECT TIME, SECTION, COUNT(*) as TOTAL,
       COUNT(STATUS) AS IN, ( COUNT(*) - COUNT(STATUS) ) as ABSENT
FROM attendance_record
GROUP BY TIME, SECTION
ORDER BY TIME