PostgreSQL中的SQL窗口函数

问题描述 投票:1回答:1

我是SQL的新手,我尝试使用PostgreSQL(9.6)查询数据库。

当我编写以下代码时,我有windows函数的错误语法:

/* 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
sql postgresql window-functions
1个回答
1
投票

您不需要子查询:

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;

你也不需要加入film,因为你没有使用该表中的任何内容。

您的查询失败,因为列列表位于SELECT子句中。 FROM列表遵循SELECT

© www.soinside.com 2019 - 2024. All rights reserved.