找到后续电影的较低评分

时间:2018-11-27 19:09:43

标签: sql postgresql

我有一张桌子电影和另一个名为 directors 的桌子,具有以下属性:

Movies               Director
------              -----------
title               name
director            country
year
genre
rating

我正在尝试查找同一导演的电影,该电影的评级低于同一导演的任何后续电影。这是我的查询:

SELECT * 
FROM movies m1
JOIN directors d ON m1.director=d.name 
WHERE EXISTS
    (
    SELECT * 
    FROM movies m2 
    WHERE (m1.rating<m2.rating 
    AND m1.year<m2.year)
    AND m1.director=m2.director
    );

我希望得到如下结果:

movie1    director1    rating-2   year1
movie2    director1    rating-4   year2
movie3    director1    rating-2   year4
movie4    director1    rating-4   year7

但是,我得到了:

movie1    director1    rating 2   year1
movie2    director1    rating 4   year2
movie3    director1    rating-4   year4
movie4    director1    rating-2   year7

我认为这不是正确的方法。 :(

1 个答案:

答案 0 :(得分:0)

您想要一个局部最小值。 。 。但相反。

select m.*
from (select m.*,
             min(m.rating) over (partition by m.director order by m.year desc rows between unbounded preceding and 1 preceding) as min_future_rating
      from movies m
     ) m
where rating < min_future_rating;