mysql - Merge two similar aggregate functions in select statement -
here's sql statement:
select distinct `class`, `student_id` , `student_name`, ( select sum( `credits` ) `stumgr_scores` b join `stumgr_courses` using ( `course_id` ) `year` =2012 , a.`student_id` = b.`student_id` ) `total_credits`, ( select sum( `credits` * `final_score` ) `stumgr_scores` c join `stumgr_courses` using ( `course_id` ) `year` =2012 , a.`student_id` = c.`student_id` ) `total_scores` `stumgr_scores` natural join `stumgr_students` `year` =2012 , `grade` =2011
you may discover these 2 select statement use aggregate functions similar. so, want merge them 1 following:
select distinct `class`, `student_id` , `student_name`, ( select sum( `credits` ) `total_credits`, sum( `credits` * `final_score` ) `total_scores` `stumgr_scores` b join `stumgr_courses` using ( `course_id` ) `year` =2012 , a.`student_id` = b.`student_id` ) `something` `stumgr_scores` natural join `stumgr_students` `year` =2012 , `grade` =2011
of course, sql statement above doesn't work , don't know do. besides, query slow because of large data, have suggestions? lot.
i have had guess @ table structure slightly, should able simplify query massively using join
s rather correlated subqueries:
select st.student_id, st.student_name, c.class, sum(sc.credits) total_credits, sum(sc.credits * sc.final_score) total_scores 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 st.student_id, st.student_name, c.class;