如何在Oracle中获取SUM的MAX

时间:2015-11-30 20:53:18

标签: sql oracle sum max

我很难让每个月看到更多电视的人和他们各自的城市。

我有三张桌子:

    house:
    id, street, city

    person:
    name, id

    visualizes:
    person, duration, date

到目前为止,我有这个,但它只会让那些看过有史以来电视节目最多的人回归:

    SELECT TO_CHAR (V.date, 'MM.YYYY'), P.name, P.id, C.city, SUM(V.duration)
    FROM visualizes V, house C, person P
    WHERE (C.id = P.house)
    AND (V.person = P.id)
    GROUP BY TO_CHAR (V.date, 'MM.YYYY'), P.name, P.id, C.city
    HAVING SUM(V.duration) IN ( SELECT MAX( SUM(V.duration))
                    FROM visualizes V, house C, person P
                    WHERE (C.id = P.house)
                    AND (V.person = P.id)
                    GROUP BY TO_CHAR (V.date, 'MM.YYYY'), P.name, P.id, C.city
                    );

1 个答案:

答案 0 :(得分:1)

使用分析函数:

SELECT pvc.*
FROM (SELECT TO_CHAR(V.date, 'MM.YYYY'), P.name, P.id, C.city,
             SUM(V.duration) as cur,
             MAX(SUM(v.duration)) OVER (PARTITION BY TO_CHAR(V.date, 'MM.YYYY')) as maxdur
      FROM person P JOIN
           visualizes V
           ON C.id = P.house JOIN
           house C
           ON V.person = P.id
      GROUP BY TO_CHAR(V.date, 'MM.YYYY'), P.name, P.id, C.city
     ) pvc
WHERE maxdur = dur;