2017-07-25 41 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;