达到阈值时如何重置累积和

how to reset cumulative sum when reached to threshold

我遇到了一个问题,我计算 cum_sum to amount 列,我希望每当 cum_sum 通过阈值 300 时重置 cum_sum 并重新计算

数据是这样的

|pk | amount  |
|:-|:-:| ---:|
|1   | 1000   |
|2   |20      |
|3   |50      |
|4   |100     |
|5   |120     |
|6   |50      |
|7   |200     |
|8   |100     |
|9   |1000    |
|10  |200     |

和预期输出

|pk | amount | cum_sum| 
|:-|:-:| ---:|
|1   | 1000   |1000|
|2   |20      |20|
|3   |50      |70 | 
|4   |100     |170|
|5   |120     |290|
|6   |50      |340|
|7   |200     |200|
|8   |100     |300|
|9   |1000    |1000|
|10  |200     |200|

由于这个问题的性质,您需要使用递归 CTE。这看起来像:

with t as (
      select t.*, row_number() over (order by pk) as seqnum
      from yourtable t
     ),
     cte as (
      select seqnum, pk. amount, amount as running_amount
      from t
      where seqnum = 1
      union all
      select t.seqnum, t.pk, t.amount,
             (case when running_amount + amount > 300 then amount
                   else running_amount + amount
              end)
      from cte join
           t
           on t.seqnum = cte.seqnum + 1
     )
select *
from cte;

递归 CTE 的确切语法因数据库而异,但它们是标准 SQL 的一部分。