1

My database "Films" contains columns: name, year (1980-2015) and rating of the film (1-10). I would like to get the BEST FILM from EVERY year like:

The Beutiful Mind 2001 rating: 8.2
Catch Me If You Can 2002 rating: 8.0

I only can think how to do it in multiple queries like:

SELECT *
FROM movies
WHERE year = 2001
ORDER BY imdb_rating DESC
LIMIT 1;

SELECT *
FROM movies
WHERE year = 2002
ORDER BY imdb_rating DESC
LIMIT 1;

etc.

How can i achieve it in one query in SQL? What's the best way? Or maybe there is no problem with multiple queries in this case? Thanks for help :)

4
  • what happens if there are 2 films with a rating of 10 on the same year? Commented May 10, 2016 at 0:48
  • SQL Server does not have limit so I removed it as a tag. Commented May 10, 2016 at 0:49
  • Is this mysql or sqlserver? You tagged both. Commented May 10, 2016 at 0:49
  • Webeng - we can just choose one from the best; SQLChao, Gordon Linoff - i am just practising SQL queries, sorry for adding other tags :) Commented May 10, 2016 at 0:55

3 Answers 3

3

One method is to use a subquery in the where clause:

select m.*
from movies m
where m.imdb_rating = (select max(m2.rating) from movies m2 where m2.year = m.year);
Sign up to request clarification or add additional context in comments.

Comments

2
select name, year from (
select 
  name, year,
  row_number() over (partition by year order by rating desc) as rt
from movies ) RankTab
where rt = 1

SQL Fiddle sample

Comments

0
SELECT name, year, MAX(rating) FROM Films WHERE GROUP BY year

Let me know if that worked for you.

1 Comment

SELECT name, year, MAX(rating) FROM Films GROUP BY year; <--- quite simple and gives me expected results, thank You :)

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.