找到分组SUM的MAX

时间:2012-11-15 13:00:12

标签: sql oracle aggregation

我有这个代码,它为我提供了每部电影的销售席位:

SELECT mName, SUM(soldSeats)
FROM movie, show, prog
WHERE movie.movieID = prog.movieID
AND prog.showID = show.showID
GROUP BY mName 

问题是要找到销售最多座位的电影,我试图添加它,但只获得没有行:

HAVING SUM(soldseats) = (SELECT MAX(SUM(soldseats)) FROM show
GROUP BY solgteplasser)

有人有建议吗?表格如下:Sum of a activity

1 个答案:

答案 0 :(得分:2)

Select test.* 
from 
(Select movie.mName, SUM(show.soldSeats) as soldseatsum
FROM movie, show, prog
WHere movie.movieId = prog.movieID
AND prog.showID = show.showID
Group by movie.mName
Order by soldseatsum DESC) test
Where rownum<=1

这样您就可以按SUM顺序排列选择 并且只使用Rownum选择第一行 这是SUm最高的行。

编辑: 如果你的SUM列中有Nulls,请确保在ORder之后添加NULLS LAST,如下所示:

.....
.....
Group by movie.mName
    Order by soldseatsum DESC NULLS LAST) test
    Where rownum<=1