Nesting Aggregate Functions - SQL

若如初见. 提交于 2019-11-30 14:56:52

问题


I want to make a SQL query which finds the catagory of awards for movies which has the highest average rating, so for a group of movies which have won a particular award, if they have a higher average rating than any other awards group of movies then it will be returned.

I tried something like this:

SELECT MAX(AVG(m."Rating"))
FROM awards a, movies m
WHERE a."Title" = m."Title"
GROUP BY a."Award"

but it seems that aggregate functions cannot be nested. How can I call the max function on the average ratings for each catagory?


回答1:


If you are only interested in the value itself, the following should do it:

SELECT MAX(avg_rating)
FROM (
    SELECT AVG(m."Rating") as avg_rating
    FROM awards a, movies m
    WHERE a."Title" = m."Title"
    GROUP BY a."Award"
) t

Otherwise Adrian's solution is better.




回答2:


This will bring your desired result:

SELECT a."Award", AVG(m."Rating")
FROM awards a, movies m
WHERE a."Title" = m."Title"
GROUP BY a."Award"
ORDER by AVG(m."Rating") desc
LIMIT 1

This will allow you not only get the MAX value, but its corresponding Award info




回答3:


Did you try this?

SELECT MAX(
   SELECT AVG(m."Rating")
   FROM awards a, movies m
   WHERE a."Title" = m."Title"
   GROUP BY a."Award"
)



回答4:


Another way is to use windowed MAX:

SELECT MAX(AVG(m."Rating")) OVER()
FROM awards a -- proper JOIN syntax
JOIN movies m ON a."Title" = m."Title"     
GROUP BY a."Award"
LIMIT 1;

db<>fiddle demo



来源:https://stackoverflow.com/questions/8141452/nesting-aggregate-functions-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!