我的数据库"电影"包含列:名称,年份(1980-2015)和电影评级(1-10)。 我希望每年都能获得最佳电影:
The Beutiful Mind 2001 rating: 8.2
Catch Me If You Can 2002 rating: 8.0
我只能想到如何在多个查询中执行此操作,例如:
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;
等
如何在SQL中的一个查询中实现它?最好的方法是什么?或者在这种情况下,多个查询可能没有问题?谢谢你的帮助:)
答案 0 :(得分:3)
一种方法是在where
子句中使用子查询:
select m.*
from movies m
where m.imdb_rating = (select max(m2.rating) from movies m2 where m2.year = m.year);
答案 1 :(得分: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
答案 2 :(得分:0)
SELECT name, year, MAX(rating) FROM Films WHERE GROUP BY year
如果这对您有用,请告诉我。