2012-06-13 177 views
1

无论如何,如果没有我向您显示表格,您将能够帮助优化此查询?所有这些疑问都源于优化SQL查询与计数表的多个连接

我原来的表有以下几列和表名为laterec-学生

-------------------------------------------------------------- 
| 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名学生迟到了,他们都只迟了一次。

+0

如果你解释你的业务逻辑,这将有所帮助。 1xlate和2xlate应该是什么意思?就像你期待我们通过阅读你的代码来弄清楚你想做什么。这很难。谢谢。 –

+0

好的,基本上这个表格包含了迟到的学生数量的数据。我编辑了上述 – d123

+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; 
+0

嗨,彼得,感谢您的回答,但是我的1xLate和2xLate不是自己的表,有子查询生成 – d123

+0

您是否尝试过查询?我也在生成这些列。 –

+0

哦,废话!我非常抱歉!是的,它的作品= D非常感谢你!我很抱歉 – d123