Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

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:

enter image description here

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?

enter image description here

The answer should actually be as the picture above.

Any help is highly appreciated.

question from:https://stackoverflow.com/questions/65867586/sql-window-function-and-joins

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why is it happening? That is what window functions do. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...