[英]Join two select statement from one table
i have a table named attendance with 2 attributes (id, remarks). 我有一个名为Attenance的表,带有2个属性(标识,备注)。 i want to display the tally of absence or late per id from the attendance table.
我想从出勤表中显示缺勤或迟到的每个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 |
currently, i can only output 2 columns, (ID and Absent) or (ID and Late) using this code: 目前,我只能使用以下代码输出2列,(ID和缺席)或(ID和后期):
SELECT id, count(remarks) AS Absent
FROM attendance
WHERE remarks = 'Absent'
GROUP BY id;
i can't display absent and late column simultaneously.. please help. 我无法同时显示缺席和后期专栏..请帮助。 thanks.
谢谢。
This is basically a PIVOT
. 这基本上是一个
PIVOT
。 If you do not have access to a PIVOT
function then, you can replicate it with an aggregate function and a CASE
statement: 如果您无权使用
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
See SQL Fiddle with Demo 参见带有演示的SQL Fiddle
Or you can use COUNT()
: 或者您可以使用
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;
Use a SUM(CASE)
construct to separate the Absent
and Late
. 使用
SUM(CASE)
构造将Absent
和Late
分开。 For each one, the CASE returns a 1 or 0 if the value is matched, and then those are added up via the aggregate SUM()
giving the total number. 对于每个值,如果值匹配,则CASE返回1或0,然后通过总计
SUM()
的总和将这些值相加。 The concept at work here is known as a 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
try: 尝试:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.