I realized there is a much simpler way to get the results:
Declare @product Table (
Product char(1)
, Location tinyint
, TransDate DATE
, TransBal int
);
Insert @product (
Product
, Location
, TransDate
, TransBal
)
Values ('A', 1, '02/01/2018', 50)
, ('A', 1, '02/15/2018', 75)
, ('A', 2, '03/01/2018', 25)
, ('A', 2, '03/06/2018', 50)
, ('B', 1, '03/01/2018', 25);
Select * From @product;
Declare @minDate date = (Select min(p.TransDate) From @product p)
, @maxDate date = dateadd(day, 1, (Select max(p.TransDate) From @product p));
With dates
As (
Select n.id
, DateValue = dateadd(day, n.id, @minDate)
From (Select row_number() over(Order By ac.object_id) - 1 As id From sys.all_columns ac) As n
)
, products
As (
Select *
, EndTransDate = lead(p.TransDate, 1, @maxDate) over(Partition By p.Product, p.Location Order By p.TransDate)
From @product p
)
Select ps.Product
, ps.Location
, TransDate = dt.DateValue
, ps.TransBal
From products ps
Inner Join dates dt On dt.DateValue >= ps.TransDate
And dt.DateValue < ps.EndTransDate
Order By
Product
, Location
, TransDate;
With this one - it will generate rows through the max end date for any product/location that does not have a following row. If there is a next date for the product/location it will use the values for that row...
Increase the variable @maxDate to include rows to the end date you want...for example, if you change @maxDate to: dateadd(day, 1, getdate()) you will get rows for each product/location through current date.
Jeffrey Williams
“We are all faced with a series of great opportunities brilliantly disguised as impossible situations.”
― Charles R. Swindoll
How to post questions to get better answers faster
Managing Transaction Logs