Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query - Calculating Previous Year Sales

Tags:

sql

I don't know anything about SQL. I currently have a query that gives me this. Sales for some products by channel/etc (please note this is a very simplified version, there's more fields) by week/period/year: enter image description here

Basically what I would need is to add a column that gives me the sales for prior year. Basically, transform the table as below. In Excel it would be a simple sumifs that would just sum the same exact criteria aside from the year which would be the previous year.

Is it possible to do this within SQL? The dataset is too large to do it within Excel.

enter image description here

like image 559
robeambro Avatar asked Mar 23 '26 19:03

robeambro


1 Answers

I think you just want lag():

select t.*,
       lag(sales) over (partition by channel, product, weekno order by yearno) as prev_sales
from t;

If I understand the data, then periodno is redundant with weekno.

like image 185
Gordon Linoff Avatar answered Mar 26 '26 15:03

Gordon Linoff