在postgresql中,如何使用窗口函数而不是使用count()函数进行计数
我正在尝试查询电影列表,将它们分类以及每部电影的出租次数。我想使用窗口函数来计算每部电影的出租次数,同时将其分组到每个类别并保留其行。
SELECT film_title, category_name,
COUNT (*) AS count_of_rentals
FROM
(SELECT f.film_id AS film_id,
f.title AS film_title,
c.name AS category_name,
r.customer_id AS customer_id,
rental_date AS rental_date
FROM film f
JOIN film_category fc
ON f.film_id = fc.film_id
JOIN category c
ON c.category_id = fc.category_id
JOIN inventory i
ON i.film_id = f.film_id
JOIN rental r
ON r.inventory_id = i.inventory_id
WHERE c.name IN ('Animation', 'Children', 'Classics', 'Comedy', 'Family', 'Music')
ORDER BY 3, 2) t1
GROUP BY 1, 2
ORDER BY 2, 1;
我能够使用计数函数获得我想要的结果,但我想使用窗口函数进行聚合。我该怎么办?先感谢您。
I'm trying to query a list of movies, classifying them into categories and the number of times each movies had been rented out. I want to use window function to count the number of times each movies had been rented out while being grouped into each categories and retaining their rows.
SELECT film_title, category_name,
COUNT (*) AS count_of_rentals
FROM
(SELECT f.film_id AS film_id,
f.title AS film_title,
c.name AS category_name,
r.customer_id AS customer_id,
rental_date AS rental_date
FROM film f
JOIN film_category fc
ON f.film_id = fc.film_id
JOIN category c
ON c.category_id = fc.category_id
JOIN inventory i
ON i.film_id = f.film_id
JOIN rental r
ON r.inventory_id = i.inventory_id
WHERE c.name IN ('Animation', 'Children', 'Classics', 'Comedy', 'Family', 'Music')
ORDER BY 3, 2) t1
GROUP BY 1, 2
ORDER BY 2, 1;
I was able to get the results I wanted using the count function but I want to use the window function to aggregate. How do I go about it? Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以修改 &尝试如下相同的查询:
IN
(partition byorder by)
您可以保留原始查询中的相同列You can modify & try the same query like below :
IN
(partition by <column> order by <column>)
you can keep the same columns which you have in your original query您不需要任何外部查询,而是需要在 count(*) 窗口函数的分区子句中提及按列分组。
You don't need any outer query rather need to mentioned the grouped by columns in count(*) window function's partition by clause.
您的查询显示每部电影和类别一行以及电影的租赁总额。窗口函数在这里没有意义,因为您不需要从所选行中派生任何值。
例如,如果您还想显示该类别的租金总额,则可以使用窗口函数来完成:
Your query shows one row per film and category along with the film's rental total. A window function would not make sense here, because there is no value you want to derive from the selected rows.
If for instance you wanted to show the category's rental total, too, that would be done with a window function: