Need to modify this query to taken previous Closing Blance- Next record Opening Balance and result create as new column nam baldiff please help Some one
select top 6500 T.ID,t.Amount, t.Description,
c.TransTypeDesc, t.OpeningCashBalance,
ClosingCashBalance, OpeningBonusBalance,
ClosingBonusBalance,CeatedDate
You can use LAG | Microsoft Learn and LEAD | Microsoft Learn function to accomplish the requerements. As you didn't provide any sample data I cannot test it but it would look like something like this:
SELECT top 6500
t.id,
t.Amount,
t.[Description],
c.TransTypeDesc,
t.OpeningCashBalance,
ClosingCashBalance,
OpeningBonusBalance,
ClosingBonusBalance,
CeatedDate,
LAG(OpeningCashBalance, 1, 0) OVER (ORDER BY id DESC) AS PrevOpeningCashBalance,
LEAD(ClosingCashBalance, 1, 0) OVER (ORDER BY id DESC) AS NextClosingCashBalance
FROM [Transaction] t
INNER JOIN TransactionTypes c
ON t.TransactionTypeId=c.TransTypeID
WHERE t.CustomerId = 27498
ORDER BY t.id DESC;
If you provide a working example with sample data I would be able to help you more specific. This is an example I created based on the image you have provided for the first two columns:
DECLARE @OpeningCashbalance TABLE
(
ID INT,
OpeningCashbalance INT
)
INSERT INTO @OpeningCashbalance
SELECT 1,14
UNION
SELECT 2,54
UNION
SELECT 3,94
UNION
SELECT 4,14
UNION
SELECT 5,54
UNION
SELECT 6,94
UNION
SELECT 7,134
UNION
SELECT 8,56
UNION
SELECT 9,96
UNION
SELECT 10,136
SELECT ID, OpeningCashbalance, LAG(OpeningCashbalance,1,-7986) OVER (ORDER BY ID) AS ClosingCashbalance
FROM @OpeningCashbalance
ORDER BY ID