如果我不向您展示表格,您是否可以帮助优化此查询?
派生所有这些查询的原始表具有以下列,该表名为 laterec-students
--------------------------------------------------------------
| studentid | name | class | latetime | waived |
--------------------------------------------------------------
| ID1111STU | Stu 1 | 1A |2012-01-09 08:09:00 |Waived |
SELECT A.class, NoStudentsLate, 1xLATE, 2xLATE FROM (
SELECT
class,
count(DISTINCT studentid) AS NoStudentsLate
FROM `laterec-students`
WHERE waived!="Waived"
GROUP BY class
) AS A
LEFT JOIN (
SELECT class, count(distinct studentid) AS 1xLATE from (
SELECT `laterec-students`.class, `laterec-students`.studentid
FROM `laterec-students`
WHERE waived!="Waived"
GROUP BY studentid
HAVING count(studentid)=1) as temp
GROUP BY class
) AS B ON A.class=B.class
LEFT JOIN (
SELECT class, count(distinct studentid) AS 2xLATE from (
SELECT `laterec-students`.class, `laterec-students`.studentid
FROM `laterec-students`
WHERE waived!="Waived"
GROUP BY studentid
HAVING count(studentid)=2) as temp
GROUP BY class
) AS C ON A.class=C.class
这就是我想要完成的
---------------------------------------------------------------------
| Class | Total # of students late | # late 1 times | # late 2 times |
---------------------------------------------------------------------
| 1A | 5 | 3 | 2 |
| 1B | 3 | 3 | 0 |
---------------------------------------------------------------------
那么这意味着,在 1A 班中,使用学生 ID 计算总共有 5 名学生迟到。在这 5 名学生中,有 3 名学生迟到了一次,2 名学生迟到了 2 次。
又是 1B 班,共有 3 个学生迟到,而且他们都只迟到了一次。