I'm having some issues writing a query summarizing some stocking information from a query.
I've been trying a few CTE (Common table Expressions ) grouping and subqueries and LAG function to try to summarize the data. Oddly I've gotten stuck on this problem the last few days.
Here is example of the data that I'm dealing with.
--Optional create table
--Drop table testdata
--Create table testdata ( Part int, StockDate date, OutOfStock bit);
with inventorydata(Part, StockDate, OutOfStock) as
(
select 1000, '1/1/2019',1
union
select 1000,'1/2/2019',1
union
select 1000, '1/3/2019',1
union
select 1000, '1/4/2019',0
union
select 1000, '1/5/2019',1
union
select 1005, '1/1/2019',0
union
select 1005,'1/2/2019',1
union
select 1005, '1/3/2019',1
union
select 1005, '1/4/2019',1
union
select 1005, '1/5/2019',0
)
--Insert into testdata ( Part,StockDate,OutOfStock)
Select Part,StockDate,OutOfStock from inventorydata
--Select * from testdata
Output
Part StockDate OutOfStock
----------- --------- -----------
1000 1/1/2019 1
1000 1/2/2019 1
1000 1/3/2019 1
1000 1/4/2019 0
1000 1/5/2019 1
1005 1/1/2019 0
1005 1/2/2019 1
1005 1/3/2019 1
1005 1/4/2019 1
1005 1/5/2019 0
I'm trying get the desired output.
Part StockDate BackInStock Occurance
----------- --------- ----------- -----------
1000 1/1/2019 1/3/2019 1
1000 1/5/2019 1/5/2019 1
1005 1/2/2019 1/4/2019 1
Any help is much appreciated. Thank you.