使用计数表优化SQL查询多个连接

时间:2012-06-13 11:37:12

标签: mysql sql

如果没有我向您展示表格,您是否有机会帮助优化此查询?

我的所有这些查询的原始表格都包含以下列,该表名为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级,总共有5名学生迟到,使用学生ID计算。在这5名学生中,有3名学生迟到了一次,2名学生迟到了两次。

同样在1B班,共有3名学生迟到,而且所有学生都只迟到一次。

1 个答案:

答案 0 :(得分:3)

我希望我理解您的查询,但以下内容适用于我的SQL Fiddle example

SELECT
  class,
  SUM(cnt > 0) AS NoStudentsLate,
  SUM(cnt = 1) AS 1xLate,
  SUM(cnt = 2) AS 2xLate
FROM
(
  SELECT class, studentid, COUNT(*) AS cnt
  FROM `laterec-students`
  WHERE waived!='Waived'
  GROUP BY class, studentid
) t
GROUP BY class;