2013-04-25 123 views
0

这里有一个SQL语句:合并两个相似的聚合函数在SELECT语句

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 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语句不工作,我不知道该怎么办。 另外,由于数据量大,查询速度很慢,您有什么建议吗?非常感谢。

+0

你可以给样品记录? – 2013-04-25 11:50:31

+0

和DB结构。因为你使用的别名非常不一致,所以不可能看到数据来自哪里 – nvanesch 2013-04-25 11:55:15

+0

那么,你可以下载数据库[here](http://rapidshare.com/files/1950426170/database.sql) – 2013-04-25 11:59:58

回答

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

哇〜!太棒了〜!非常感谢〜! – 2013-04-25 12:09:47