Duplicating rows based on multiple conditions

Viewed 27

I have a dataset where I need to split a single row into multiple rows based on more than one condition.

My data and data set is as follows:

declare @data table
(
item varchar(5)
,batch_stock int
,expiry_date datetime
,avg_weekly_sales int
)

insert into @data 
values 
    ('67007',   50, '2022-10-11 00:00:00.000',47),
    ('67007',   125,    '2022-11-16 00:00:00.000',47),
    ('67004',   71, '2022-10-11 00:00:00.000',51),
    ('67004',   183,'2022-11-07 00:00:00.000',51),
    ('67005',   138,    '2022-11-07 00:00:00.000',36),
    ('67005',   140,    '2022-10-24 00:00:00.000',36)

select 
    item  
    ,batch_stock  
    ,expiry_date  
    ,avg_weekly_sales 
    ,batch_stock/avg_weekly_sales as weeks_of_stock
from @data

This is the resulting output currently:

Data Output

What I am wanting to do is, for each item, I need to split the row into multiple rows based on the item / expiry_date / weeks of stock.

This is the desired result is:

result desired

For each item and batch, I need to subtract from it's batch_stock the Avg weekly sales until the remaining stock is lower than the avg weekly sales. One row for each week the stock is being taken out.

I know I have to use recursive CTE to accomplish this. but I have no idea how to do them based on multiple conditions!

0 Answers
Related