I have a table like this
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)
);
I want to compare the current year’s sale with the last year’s sale using LAG
window function.
Like this:
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;
but I can’t get the desired result and I got this error
ERROR: column "annual_sale" does not exist
How to compare a record (row) to previous record for an aggregated column?
3
Answers
You should calculate aggregated
SUM
column first, then useLAG
to calculate the difference.See demo here.
It’s because column
annual_sale
really doesn’t exist: alias is not allowed in lead. You should useSUM(amount)
(or use sub-query).Also you don’t need to partition your lag.
Fiddle here
I suggest aggregating by year first, then taking the lag in sales.