在select语句中合并两个类似的聚合函数

时间:2013-04-25 11:44:36

标签: mysql sql aggregate-functions

这是一个SQL语句:

SELECT DISTINCT  `class`, `student_id` , `student_name`,
( 
    SELECT SUM(  `credits` ) 
    FROM  `stumgr_scores` B
    JOIN  `stumgr_courses` USING (  `course_id` ) 
    WHERE  `year` =2012 AND A.`student_id` = B.`student_id`
) AS  `total_credits`,
( 
    SELECT SUM( `credits` *  `final_score` )
    FROM  `stumgr_scores` C
    JOIN  `stumgr_courses` USING (  `course_id` ) 
    WHERE  `year` =2012 AND A.`student_id` = C.`student_id`
) AS `total_scores`
FROM  `stumgr_scores` A
NATURAL JOIN  `stumgr_students` 
WHERE  `year` =2012 AND  `grade` =2011

您可能会发现使用聚合函数的这两个select语句是相似的。所以,我想将它们合并为一个如下:

SELECT DISTINCT  `class`, `student_id` , `student_name`,
( 
    SELECT 
        SUM(  `credits` ) AS  `total_credits`, 
        SUM( `credits` *  `final_score` ) AS  `total_scores`
    FROM  `stumgr_scores` B
    JOIN  `stumgr_courses` USING (  `course_id` ) 
    WHERE  `year` =2012 AND A.`student_id` = B.`student_id`
) AS `something`
FROM  `stumgr_scores` A
NATURAL JOIN  `stumgr_students` 
WHERE  `year` =2012 AND  `grade` =2011

当然,上面的SQL语句不起作用,我不知道该怎么做。 此外,由于数据量大,查询速度很慢,您有什么建议吗?非常感谢。

1 个答案:

答案 0 :(得分:2)

我不得不稍微猜测一下你的表结构,但你应该能够通过使用JOIN而不是相关的子查询来大规模地简化这个查询:

SELECT  st.student_id,
        st.student_name,
        c.class,
        SUM(sc.credits) AS total_credits,
        SUM(sc.credits * sc.final_score) AS total_scores
FROM    stumgr_students st
        INNER JOIN stumgr_scores sc
            ON sc.student_id = st.student_id
        INNER JOIN stumgr_courses c
            ON c.course_id = st.course_id
GROUP BY st.student_id, st.student_name, c.class;