You can achieve this using Window Functions - however you will need to take care in your ORDER
clause in the function and ensure that your data is ordered in a definable way.
For your example, I have specified the order to be by customer_no DESC
first of all and then by number ASC
The condition is then whether the Net value from the previous row is negative and if so add the current row's values to it. I use ISNULL(xxx, 0)
to account of the first row that doesn't have a LAG
value.
SELECT number, customer_no, invoice_no, due_date, AR, ADV,
CASE
WHEN ISNULL(LAG (AR + ADV) OVER (ORDER BY customer_no DESC, number ASC), 0) < 0
THEN AR + ADV + ISNULL(LAG (AR + ADV) OVER (ORDER BY customer_no DESC, number ASC), 0)
ELSE AR + ADV
END as Net
FROM CumulativeSum
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.