I have a table with these columns: id, sku, price, date
CREATE TABLE price_log (
id int NOT NULL PRIMARY KEY,
sku text NOT NULL,
date date NOT NULL,
price real NOT NULL,
CONSTRAINT date_sku UNIQUE (sku,date)
)
I want to get a report of change price in overtime.
My desired output is:
sku old_price new_price change_date
A 10 11 2022-01-03
B 1 5.99 2022-01-02
B 5.99 3.5 2022-01-03
B 3.5 12 2022-01-04
Right now the best I could do is to use LAG()
function:
WITH cte AS (
SELECT sku, price, MAX(date) AS date
FROM price_log
GROUP BY sku, price
)
SELECT sku, price, date,
LAG(price,1) OVER (
PARTITION BY sku
ORDER BY date
) AS old_price
FROM cte
3
Answers
There are N ways to do that. For example one would be to use lateral:
DbFiddle demo
Try the following:
See a demo.
Fiddle