I have Following table:
I want output Like Opening = Previous Closing group with ItemGroupMasterId & Calculate Closing Formula Like (OPUnitQuantity + TrnIwUnitQuantity) - TrnOWUnitQuantity.
I am using SQL Server 2008 r2.
Table Script
CREATE TABLE [dbo].[TestMaster..TestData]( [MONTHS] [smallint] NULL, [YearS] [smallint] NULL, [ItemGroupMasterId] [smallint] NULL, [OPUnitQuantity] [numeric](18, 3) NULL, [TrnIwUnitQuantity] [numeric](18, 3) NULL, [TrnOWUnitQuantity] [numeric](18, 3) NULL, [closing] [numeric](18, 3) NULL ) ON [PRIMARY] INSERT INTO TestMaster..TestData (MONTHS,YearS,ItemGroupMasterId,OPUnitQuantity,TrnIwUnitQuantity,TrnOWUnitQuantity,closing) Values (4,2021,30,27534.300,83792.100,102161.360,9165.040) INSERT INTO TestMaster..TestData (MONTHS,YearS,ItemGroupMasterId,OPUnitQuantity,TrnIwUnitQuantity,TrnOWUnitQuantity,closing) Values (5,2021 ,30 ,0 ,56806.49 ,52938.08, 0) INSERT INTO TestMaster..TestData (MONTHS,YearS,ItemGroupMasterId,OPUnitQuantity,TrnIwUnitQuantity,TrnOWUnitQuantity,closing) Values (6 ,2021, 30 ,0 ,43508.02 ,43367.98,0) INSERT INTO TestMaster..TestData (MONTHS,YearS,ItemGroupMasterId,OPUnitQuantity,TrnIwUnitQuantity,TrnOWUnitQuantity,closing) Values (7, 2021, 30, 0 ,101539, 97577.68,0) INSERT INTO TestMaster..TestData (MONTHS,YearS,ItemGroupMasterId,OPUnitQuantity,TrnIwUnitQuantity,TrnOWUnitQuantity,closing) Values (8, 2021, 30 ,0 ,109556.92, 106798.7 ,0) INSERT INTO TestMaster..TestData (MONTHS,YearS,ItemGroupMasterId,OPUnitQuantity,TrnIwUnitQuantity,TrnOWUnitQuantity,closing) Values (9, 2021, 30, 0 ,115159.96 ,110613.14 ,0) INSERT INTO TestMaster..TestData (MONTHS,YearS,ItemGroupMasterId,OPUnitQuantity,TrnIwUnitQuantity,TrnOWUnitQuantity,closing) Values (11, 2021 ,30, 0 ,101398.135, 108433.86,0) INSERT INTO TestMaster..TestData (MONTHS,YearS,ItemGroupMasterId,OPUnitQuantity,TrnIwUnitQuantity,TrnOWUnitQuantity,closing) Values (12, 2021 ,30 ,0 ,110334.195 ,112894.35,0) INSERT INTO TestMaster..TestData (MONTHS,YearS,ItemGroupMasterId,OPUnitQuantity,TrnIwUnitQuantity,TrnOWUnitQuantity,closing) Values (1 ,2022 ,30 ,0 ,98296.32 ,87840.05,0) INSERT INTO TestMaster..TestData (MONTHS,YearS,ItemGroupMasterId,OPUnitQuantity,TrnIwUnitQuantity,TrnOWUnitQuantity,closing) Values (2, 2022 ,30, 0 ,22868.14 ,44320.6,0) INSERT INTO TestMaster..TestData (MONTHS,YearS,ItemGroupMasterId,OPUnitQuantity,TrnIwUnitQuantity,TrnOWUnitQuantity,closing) Values (3 ,2022 ,30, 0 ,75159.48 ,56382.23,0) INSERT INTO TestMaster..TestData (MONTHS,YearS,ItemGroupMasterId,OPUnitQuantity,TrnIwUnitQuantity,TrnOWUnitQuantity,closing) Values (4 ,2021 ,34 ,1194 ,1570 ,1444 ,1320) INSERT INTO TestMaster..TestData (MONTHS,YearS,ItemGroupMasterId,OPUnitQuantity,TrnIwUnitQuantity,TrnOWUnitQuantity,closing) Values (5 ,2021 ,34, 0 ,648, 561 ,0) INSERT INTO TestMaster..TestData (MONTHS,YearS,ItemGroupMasterId,OPUnitQuantity,TrnIwUnitQuantity,TrnOWUnitQuantity,closing) Values (6 ,2021 ,34, 0 ,526 ,879 ,0)