简体   繁体   中英

SQL: Column Must Appear in the GROUP BY Clause Or Be Used in an Aggregate Function

I'm doing what I would have expected to be a fairly straightforward query on a modified version of the imdb database:

select primary_name, release_year, max(rating)
from titles natural join primary_names natural join title_ratings
group by year
having title_category = 'film' and year > 1989;

However, I'm immediately running into

"column must appear in the GROUP BY clause or be used in an aggregate function."

I've tried researching this but have gotten confusing information; some examples I've found for this problem look structurally identical to mine, where others state that you must group every single selected parameter, which defeats the whole purpose of a group as I'm only wanting to select the maximum entry per year.

What am I doing wrong with this query?

Expected result: table with 3 columns which displays the highest-rated movie of each year.

If you want the maximum entry per year, then you should do something like this:

select r.*
from ratings r
where r.rating = (select max(r2.rating) where r2.year = r.year) and
      r.year > 1989;

In other words, group by is the wrong approach to writing this query.

I would also strongly encourage you to forget that natural join exists at all. It is an abomination. It uses the names of common columns for joins. It does not even use properly declared foreign key relationships. In addition, you cannot see what columns are used for the join.

While I am it, another piece of advice: qualify all column names in queries that have more than one table reference. That is, include the table alias in the column name.

If you want to display all the columns you can user window function like:

select primary_name, year, max(rating) Over (Partition by year) as rating
from titles natural 
join primary_names natural join ratings
where title_type = 'film' and year > 1989;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM