Этот запрос вернет всю информацию о фильмах для лучших фильмов N (со связями) по жанрам, взятым напрокат в данный период времени.
declare @StartDate date = '20190601'
,@EndDate date = '20190630'
,@Top int = 3
;With RentalCounts as
(
SELECT genre, mv.movie_id, Count(*) Ct
FROM MOVIE mv
INNER JOIN DVD dvd ON dvd.movie_id = mv.movie_id
INNER JOIN RENTAL rt ON rt.dvd_id = dvd.dvd_id
WHERE rt.[RentalDate] between @StartDate and @EndDate
group by genre, mv.movie_id
)
, ranked as
(
select *, ranked = rank() over (partition by movie_id, genre order by Ct desc)
from RentalCounts
)
select mv.*
from ranked r
join movie m on movie.movie_id = r.MovieID
where ranked.Ct <=@top