简体   繁体   中英

SQL How to stop cummulative sum when the value is positive (+)

I'm trying to find a solution to create a cumulative sum with some logic, I have data like this:

在此处输入图像描述

We must add Column Net with Condition:

  • first row, sum AR and ADV Column
  • next row is sum with the result of first row so on
  • stop cumulative sum when the result is positive +

Expected result is:

在此处输入图像描述

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM