[英]SQL window function and joins
My query is as follows:我的查询如下:
SELECT
category_name, film_title, rental_count
FROM
(SELECT
c.name AS category_name, f.title AS film_title,
COUNT(r.rental_date) OVER (PARTITION BY f.title) AS rental_count
FROM
category c
JOIN
film_category fc ON fc.category_id = c.category_id
JOIN
film f ON fc.film_id = f.film_id
JOIN
inventory i ON i.film_id = f.film_id
JOIN
rental r ON i.inventory_id = r.inventory_id) t1
WHERE
category_name IN ('Animation', 'Children', 'Classics', 'Comedy', 'Family', 'Music')
ORDER BY
1, 2
And the results are as follows:结果如下:
As you can see that the title of the movie is repeated, as you already know, it shouldn't.如您所见,电影的标题重复了,正如您已经知道的那样,它不应该重复。 However, I can't understand why it is happening?
但是,我不明白为什么会这样?
The answer should actually be as the picture above.答案其实应该如上图。
Any help is highly appreciated.非常感谢任何帮助。
Why is it happening?为什么会这样? That is what window functions do.
这就是 window 函数的作用。 They don't reduce the number of rows.
它们不会减少行数。 That add new columns on existing rows (typically with data gathered from multiple rows).
在现有行上添加新列(通常是从多行收集的数据)。
You simply want an aggregation:您只需要一个聚合:
SELECT c.name AS category_name, f.title AS film_title,
COUNT(r.rental_date) as rental_count
FROM category c JOIN
film_category fc
ON fc.category_id = c.category_id JOIN
film f
ON fc.film_id = f.film_id JOIN
inventory i
ON i.film_id = f.film_id JOIN
rental r
ON i.inventory_id = r.inventory_id
WHERE c.category_name IN ('Animation', 'Children', 'Classics', 'Comedy', 'Family', 'Music')
GROUP BY 1, 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.