2013-04-25 120 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