简体   繁体   English

SQL 值为正(+)时如何停止累计

[英]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第一行,总和 AR 和 ADV 列
  • 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.您可以使用 Window 函数来实现此目的 - 但是您需要注意 function 中的ORDER子句,并确保您的数据以可定义的方式排序。

For your example, I have specified the order to be by customer_no DESC first of all and then by number ASC对于您的示例,我首先将订单指定为customer_no DESC ,然后是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.我使用ISNULL(xxx, 0)来说明没有LAG值的第一行。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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