15

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?

4 Answers 4

15

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.

Sign up to request clarification or add additional context in comments.

Comments

9

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

1 Comment

@Julian I never said LIMIT is SQL standard. It solves OP issue because LIMIT is also available in PostGreSQL (not only MySQL!), which is OP's RDBMS.
4

Did you try this?

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

2 Comments

Thanks, but that has a syntax error "at or near SELECT". Not sure what that would be
@steve, Commenting the inner SELECT SQL with a set of braces would solve that error. The Braces force the executing of the SELECT Scalar query before the MAX() kicks in.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.