MySQL查询Group wise Summary

时间:2017-07-25 10:37:05

标签: mysql

我的表喜欢这个

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 Query来获取这样的输出。

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

6 个答案:

答案 0 :(得分:0)

这应该有效:

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

如果您的字段值对“缺席”和“存在”有不同的拼写,也会出现问题。

答案 1 :(得分:0)

由于“现在”一词存在拼写问题。 这应该可以正常工作。

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

答案 2 :(得分: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;

答案 3 :(得分:-1)

SELECT StudentID,Date,Status FROM Attendance WHERE StudentID = 1

SELECT StudentID,Date,Status FROM Attendance WHERE StudentID = 2

答案 4 :(得分:-1)

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

尝试以上查询。

答案 5 :(得分:-1)

试试这个......

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