I would like to compute for the beginning and ending inventory. The formula is Beginning Inventory + Purchases = Ending Inventory. The results should be this:
Drop table if exists #Purchases
create table #Purchases
(ReportingDate date,
Purchases numeric(10,2))
insert into #Purchases values
('11/1/2018',77000),
('11/2/2018',100000),
('11/8/2018',0),
('11/9/2018',0),
('12/1/2018',164000),
('12/8/2018',0),
('12/15/2018',0)
select ReportingDate ,
Purchases as BeginningInventory,
SUM (Purchases) OVER (ORDER BY ReportingDate) AS EndingInventory
from #Purchases
use tempdb
go
Drop table #Purchases
go
create table #Purchases
(rn int identity(1,1) ,
ReportingDate date,
Purchases numeric(10,2))
go
insert into #Purchases values
('11/1/2018',77000),
('11/2/2018',100000),
('11/8/2018',0),
('11/9/2018',0),
('12/1/2018',164000),
('12/8/2018',0),
('12/15/2018',0)
go
select * from #Purchases
go
recursive CTE .. SQL
; with rec_cte
AS (SELECT *,
CAST (0.00 + Purchases AS numeric(10,2) ) as grp
FROM #Purchases
WHERE rn = 1
UNION ALL
SELECT a.*,
CAST (a.Purchases + b.grp AS numeric(10,2) ) as grp
FROM #Purchases a
JOIN rec_cte b
ON a.rn = b.rn + 1)
SELECT * from rec_cte
go
;
with cte as(
select * ,SUM(Purchases) OVER ( ORDER BY ReportingDate
ROWS BETWEEN UNBOUNDED PRECEDING
AND 1 PRECEDING) as BeginningInventory from #Purchases)
select ReportingDate,isnull(BeginningInventory,0)as BeginningInventory,Purchases,SUM (Purchases) OVER (ORDER BY ReportingDate) AS EndingInventory from cte