[英]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:我们必须添加具有条件的列网:
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.