我正在使用 DVD 租赁数据库,并试图找出每月租赁最多的 DVD 类别,而不关心年份。我已经制作了一个详细的表格,其中包含数据库中的每个租赁及其租赁 ID、租赁月份、库存 ID 和类别。我希望从详细表中获取信息并创建一个汇总表,其中有一列表示 12 个月,另一列显示该月最受欢迎的类别以及该月的总租金以及如何其中许多属于最受欢迎的类别。
我尝试使用循环对 12 个月进行排序,因为我希望避免编写相同的代码 12 次。我似乎无法让循环正常工作,而且我什至不确定这是否是我应该采取的方向。有没有更有效的方法来获得我正在寻找的东西?
不需要过程语言。此查询将得到您想要的结果:
with counts as (
select rental_month, category, count(1) as category_count
from detailed_monthly_rentals
group by rental_month, category
)
select distinct on (rental_month) rental_month,
category as most_popular_category,
sum(category_count)
over (partition by rental_month) as total_rentals,
category_count as rentals_for_most_popular_category
from counts
order by rental_month, category_count desc;