2017-07-25 46 views
2

我喜歡這張我對集團明智摘要SQL代碼

Attendance 
---------- 

Studentid | Date  | Status 
-------------------------------- 
1   | 2017-01-01 | Present 
1   | 2017-01-02 | Present 
1   | 2017-01-03 | Absent 
1   | 2017-01-04 | Presnt 
2   | 2017-01-01 | Absent 
2   | 2017-01-02 | Present 
2   | 2017-01-03 | Absent 
2   | 2017-01-04 | Presnt 

我想寫一個MySQL查詢得到這樣的輸出。

StudentID | PresentCount | AbsentCount 
1   |  3  |  1 
2   |  2  |  2 

回答

0

SELECT StudentID,日期,狀態由出席WHERE StudentID = 1

SELECT StudentID,日期,狀態由出席WHERE StudentID = 2

0
SELECT Studentid, 
    SUM(Status='Present') PresentCount , 
    SUM(Status='Absent') AS AbsentCount FROM Attendance 
    GROUP BY Studentid 

嘗試上述查詢。

0

試試這個....

SELECT 
    Studentid, 
    sum(case when Status = 'Present' then 1 else 0 end) AS PresentCount, 
    sum(case when Status = 'Absent' then 1 else 0 end) AS AbsentCount 
FROM 
    Attendance 
GROUP BY 
    Studentid 
0

這應該工作:

SELECT StudentId, SUM(Status='Present') as PresentCount, SUM(Status='Absent') AS AbsentCount FROM Attendance GROUP BY StudentId; 

也將有一個問題,如果你的域值有「缺席」和「存在」不同的拼法。

0

由於您對'現在'這個詞有一些拼寫問題。 這應該很好。

SELECT Studentid AS StudentID ,SUM(Status !='Absent') PresentCount , 
    SUM(Status='Absent') AS AbsentCount FROM Attendance 
    GROUP BY Studentid 
0

運行此查詢。這是你想要的。這裏是樣品fiddle

select id, max(PresentCount), max(AbsentCount) from (select id, sum(status='Present') as PresentCount, sum(status='absent') as AbsentCount from Student group by id, status) as table1 group by id;