SUM一个分组列

时间:2014-10-21 20:23:32

标签: mysql sql

我想总结一下" Total Inservice Hours"对于每个用户,但我得到"错误代码:1111。无效使用组功能"尽我所有的努力。一次尝试是围绕" Total Inservice Hours"字段,然后按u.id分组。

这是我的SQL:

SELECT u.id,"Name",
atstat.grade,IFNULL(c.total_ceus,0) as max_ceus,c.id as courseid,atsess.id as sessid, count(c.total_ceus) as numsess, IFNULL(ROUND(((SUM(grade)/count(c.total_ceus))*total_ceus)/100,2),0) as "Total Inservice Hours"
FROM mdl_user u,mdl_course c
JOIN mdl_course_modules cm ON c.id = cm.course 
JOIN mdl_attendance_sessions atsess ON cm.instance = atsess.attendanceid
JOIN mdl_attendance_log atlog ON atlog.sessionid = atsess.id 
JOIN mdl_attendance_statuses atstat ON atstat.id = atlog.statusid 
WHERE u.id = atlog.studentid AND (u.id = 3882) AND c.total_ceus > 0
GROUP by u.id,c.id
ORDER BY u.id DESC LIMIT 300

以下是该查询的结果: enter image description here

我尝试了GROUP BY u.id,但我得到了这个结果: enter image description here

我真正关心的唯一领域是u.id和Total Inservice Hours。其余的只是用于调试。

所需输出将是总服务时间的总和,在此示例中为111.

谢谢!

编辑: 无效使用组函数错误SQL:

SELECT u.id,"Name",
atstat.grade,IFNULL(c.total_ceus,0) as max_ceus,c.id as courseid,atsess.id as sessid, count(c.total_ceus) as numsess, SUM(IFNULL(ROUND(((SUM(grade)/count(c.total_ceus))*total_ceus)/100,2),0)) as "Total Inservice Hours"
FROM mdl_user u,mdl_course c
JOIN mdl_course_modules cm ON c.id = cm.course 
JOIN mdl_attendance_sessions atsess ON cm.instance = atsess.attendanceid
JOIN mdl_attendance_log atlog ON atlog.sessionid = atsess.id 
JOIN mdl_attendance_statuses atstat ON atstat.id = atlog.statusid 
WHERE u.id = atlog.studentid AND (u.id = 3882) AND c.total_ceus > 0
GROUP by u.id
ORDER BY u.id DESC LIMIT 300

1 个答案:

答案 0 :(得分:2)

你不能将一个聚合函数包装在另一个聚合函数中。

您需要将原始查询放在子查询中,以便对其中一个列求和。由于您只对ID和总在职时间感兴趣,因此您可以省略其他SELECT列。

SELECT id, SUM(`Total Inservice Hours`) AS "Total Inservice Hours"
FROM (SELECT u.id, IFNULL(ROUND(((SUM(grade)/count(c.total_ceus))*total_ceus)/100,2),0) as "Total Inservice Hours"
    FROM mdl_user u,mdl_course c
    JOIN mdl_course_modules cm ON c.id = cm.course 
    JOIN mdl_attendance_sessions atsess ON cm.instance = atsess.attendanceid
    JOIN mdl_attendance_log atlog ON atlog.sessionid = atsess.id 
    JOIN mdl_attendance_statuses atstat ON atstat.id = atlog.statusid 
    WHERE u.id = atlog.studentid AND (u.id = 3882) AND c.total_ceus > 0
    GROUP by u.id,c.id
    ORDER BY u.id DESC LIMIT 300) AS subq
GROUP BY id