mysql – 从一个表中加入两个select语句

我有一个名为出勤的表,有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;

我不能同时显示缺席和晚期列..请帮忙.谢谢.

最佳答案 这基本上是一个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 with Demo

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

点赞