Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting Aggregate Functions - SQL

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?

like image 998
steve Avatar asked Nov 15 '11 18:11

steve


People also ask

Can you nested aggregate functions in SQL?

You can't nest aggregate functions, and must instead place the inner one in a subquery.

How many aggregate functions can be nested first?

You can nest any number of the window functions LEAD and LAG, but you cannot nest more than one aggregate function within another aggregate function.

What does nesting mean in SQL?

In relational databases, a nested table is a table that is embedded within another table. Individual elements can be inserted, updated, and deleted in a nested table.


1 Answers

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.

like image 100
a_horse_with_no_name Avatar answered Sep 22 '22 08:09

a_horse_with_no_name