[英]Join two select statement from one table
我有一個名為Attenance的表,帶有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和缺席)或(ID和后期):
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
或者您可以使用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;
使用SUM(CASE)
構造將Absent
和Late
分開。 對於每個值,如果值匹配,則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
嘗試:
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.