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语句不工作,我不知道该怎么办。 另外,由于数据量大,查询速度很慢,您有什么建议吗?非常感谢。
你可以给样品记录? – 2013-04-25 11:50:31
和DB结构。因为你使用的别名非常不一致,所以不可能看到数据来自哪里 – nvanesch 2013-04-25 11:55:15
那么,你可以下载数据库[here](http://rapidshare.com/files/1950426170/database.sql) – 2013-04-25 11:59:58