Welcome to Microsoft T-SQL Q&A Forum!
Please check this:
Create table #test
(
InvoiceNo nvarchar(20),
InvoiceAmount money,
RetailnvoiceProductAmount money,
NoRetailnvoiceProductAmount money,
PaymentDate datetime,
PaymentAmount money
)
Insert into #test values
('INV-002528',100,80,20,'2022-04-01',25),
('INV-002528',100,80,20,'2022-04-12',35),
('INV-002528',100,80,20,'2022-04-26',25),
('INV-002528',100,80,20,'2022-05-01',15)
;
With cte as
(
select *,sum(PaymentAmount)OVER(PARTITION BY InvoiceNo
ORDER BY PaymentDate
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) -NoRetailnvoiceProductAmount as column1
from #test
),cte1 AS
(
Select *,LAG(column1,1,-1)OVER(PARTITION BY InvoiceNo
ORDER BY PaymentDate) AS Column2
From cte
)
select InvoiceNo,InvoiceAmount,RetailnvoiceProductAmount,NoRetailnvoiceProductAmount,PaymentDate, PaymentAmount ,case when column1 <0 and Column2<0 then 0
when column1>0 and column2<0 then column1
else PaymentAmount
end as RetailProductme_Amount
from cte1
Best regards,
Bert Zhou
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.