如何将每个组的结果与SQL中的整个组间指标进行比较

时间:2014-11-03 02:43:31

标签: mysql sql

我的问题是,当我试图从GROUP BY结果中获得均值时,我无法弄清the 10th question。我的错误代码如下

SELECT tc.staff,SUM(ev.duration)
FROM 
teaches tc
JOIN 
event ev
ON 
tc.event = ev.id
GROUP BY tc.staff
HAVING SUM(ev.duration)>AVG(SUM(ev.duration))

2 个答案:

答案 0 :(得分:0)

SELECT count(rr.staff)
FROM (
    SELECT  tc.staff,
        SUM(ev.duration) as 'total'
    FROM 
            teaches tc,
            staff st,
            event ev
    WHERE   st.id = tc.staff
    AND tc.event = ev.id
    GROUP BY tc.staff
    HAVING total > (SELECT AVG(ss.total) as 'average'
            FROM  (SELECT tc.staff,
                            SUM(ev.duration) as 'total'
                    FROM 
                            teaches tc,
                            staff st,
                            event ev
                    WHERE   st.id = tc.staff
                    AND tc.event = ev.id
                    GROUP BY tc.staff) ss)) rr;

答案 1 :(得分:-1)

更改此

HAVING SUM(ev.duration)>AVG(SUM(ev.duration))

到这个

HAVING SUM(ev.duration)>AVG(ev.duration)