如何计算SQL中两行之间的差异[PostgreSQL] -对于聚合列

gab6jxml  于 2023-04-11  发布在  PostgreSQL
关注(0)|答案(3)|浏览(142)

我有一张这样的table

CREATE TABLE fake_sales
(
    group_id INT NOT NULL,
    year SMALLINT CHECK(year > 0),
    amount DECIMAL(10, 2) NOT NULL,
    PRIMARY KEY(year, group_id)
);

我想使用LAG窗口函数比较今年的销售和去年的销售额。
就像这样:

SELECT
    year,
    SUM(amount) AS annual_sale,
    LAG(annual_sale, 1) OVER (PARTITION BY year ORDER BY year) change_amount
FROM fake_sales
GROUP BY year;

但是我不能得到想要的结果,我得到了这个错误
您访问的页面不存在!
如何比较一个记录(行)与聚合列的前一个记录?

dldeef67

dldeef671#

这是因为列annual_sale实际上不存在:不允许在lead中使用alias。您应该使用SUM(amount)(或使用子查询)。
你也不需要划分你的滞后。

SELECT
    year,
    SUM(amount) AS annual_sale,
    LAG(SUM(amount)) OVER (
        ORDER BY year
    ) - SUM(amount) change_amount
FROM fake_sales
GROUP BY year;

小提琴here

rqqzpn5f

rqqzpn5f2#

我建议先按年汇总,然后再考虑销售额的滞后。

SELECT
    year,
    SUM(amount) AS annual_sales,
    LAG(SUM(amount)) OVER (ORDER BY year) AS prev_year_sales
FROM fake_sales
GROUP BY year
ORDER BY year;
9gm1akwq

9gm1akwq3#

您应该首先计算聚合的SUM列,然后使用LAG计算差值。

SELECT 
    year,
    annual_sale,
    (annual_sale - LAG(annual_sale) OVER (ORDER BY year)) AS change_amount
FROM  
    (SELECT
        year,
        SUM(amount) AS annual_sale
    FROM fake_sales
    GROUP BY year) data;

请参见演示here

相关问题