Skip to content
Advertisement

Use SQL to find best 4 consecutive weeks

I have a dataset that has a product, weeknumber, and sales for that week.

enter image description here

I am trying to find the 4 best consecutive sales weeks in the data, so for example, Product A’s 4 best weeks are 1-4 and Product S’s best weeks are 5-8

I am using SQL to query the table to return the 4 best consecutive weeks & the totals during those weeks (grouping by product)

I am struggling on how to tackle this as I am not an expert in SQL.

So far, I have tried using a lag + subquery to create lags at intervals 1,2,3, & 4. My thought is to do a running total for each new lag column & then find the max value.

I created the lag tables, but something is happening in my ‘over’ statement that is reordering the output for the lags.

I have no idea if this is a good way to tackle the problem, but I have researched and not found anything that can help me for this problem.

Advertisement

Answer

I provide you a sample sql on MySQL. You can use it in other sql languages simply with change CONCAT function.

Result will be:

enter image description here

And you can find max of sumSale with corresponding weeks.

I provide you the MS SQL sample below which using temp table to do more query:

Result will be as: enter image description here

In Oracle you can use simply IN clause instead of JOIN for last section.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement