问题
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