Search code examples
sqlpostgresqlwindow-functions

SQL windows function in PostgreSQL


I am new in SQL and I try to query a database using PostgreSQL (9.6).

When I write the following code I have and error syntax with the windows function:

/* Ranking total of rental movie by film category (I use the sakila database) */

SELECT category_name, rental_count
FROM
    (SELECT c.name category_name, Count(r.rental_id) rental_count
    FROM category c
    JOIN film_category USING (category_id)
    JOIN inventory USING (film_id)
    JOIN rental r USING (inventory_id)
    JOIN film f USING (film_id)
    GROUP BY 1, 2
    ORDER by 2, 1
     ) sub
RANK() OVER (PARTITION BY category_name ORDER BY rental_count DESC) AS total_rank

Solution

  • You don't need a subquery:

    SELECT c.name as category_name, COUNT(*) as rental_count,
           ROW_NUMBER() OVER (PARTITION BY c.name ORDER BY COUNT(*) DESC)
    FROM category c JOIN
         film_category USING (category_id) JOIN
         inventory USING (film_id) JOIN
         rental r USING (inventory_id) JOIN
         film f USING (film_id)
    GROUP BY 1
    ORDER by 2, 1;
    

    You also don't need the join to film, because you are using nothing from that table.

    Your query fails because the column list goes in the SELECT clause. The FROM list follows the SELECT.