这是我关于DVD出租的任务。问题是找到给定类型的前三名著名租借电影。这是我的桌子。
https://drive.google.com/drive/folders/17RuEb-o8tXsAHGYAbjmQmlJaYZZUAEeE?usp=sharing。
下面是我一半完成的怪异代码。
SELECT TOP(3)
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 movie_id = movie_id
答案 0 :(得分:0)
您有一个好的开始。如果要获得租借最多的电影,则要查询该电影,然后计算租借的次数。然后,选择前3个结果,并按降序排列,并包含WITH TIES提示,以确保您包含与租借次数相同的结果。
SELECT TOP 3 WITH TIES mv.movie, COUNT(rt.id) AS times_rented
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
GROUP BY mv.movie
ORDER BY COUNT(rt.id) DESC
答案 1 :(得分:0)
此查询将返回给定时间段内租借的前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