按年份选择2个最高计数(值)

时间:2019-03-17 00:18:34

标签: sql postgresql greatest-n-per-group

我有一个postgresql-9.6数据库,我们将其命名为sales,如下所示:

sale_id   customer_id   sale_date    price
1         20            2017-01-05   2000
2         150           2017-05-26   1500
3         121           2017-07-07   2560
4         121           2017-12-25   3000
5         214           2018-02-11   2550
6         17            2018-04-21   2500
7         20            2018-07-01   3000
8         121           2019-07-01   2568

我每年需要找到前2名客户。

我被卡在这样的东西上:

SELECT 
   date_part('year', sale_date) AS year, 
   customer_id, 
   sum(price) AS Total 
FROM 
   sales 
GROUP BY 1,2 
ORDER BY 1,3 DESC 
LIMIT 2

我正在尝试获得这样的东西:

year     customer_id      Total
2017     121              5560
2017     20               2000
2018     20               3000
2018     214              2550
2019     121              2568

1 个答案:

答案 0 :(得分:1)

您可以使用汇总来计算每位客户和每年的总销售额,然后使用窗口函数ROW_NUMBER(自Postgres 9.4起可用)来过滤每年的前2位客户:

SELECT
    sale_year,
    customer_id,
    total_price
FROM (
    SELECT 
        x.*,
        ROW_NUMBER() OVER(PARTITION BY sale_year ORDER BY total_price DESC) rn
    FROM (
        SELECT
            date_part('year', sale_date) AS sale_year, 
            customer_id, 
            sum(price) AS total_price 
        FROM sales
        GROUP BY date_part('year', sale_date), customer_id
    ) x
) y 
WHERE rn <= 2
ORDER BY sales_year, rn