递归累积总和达到一定值Postgres

时间:2018-01-02 11:51:46

标签: postgresql recursion

我的数据看起来像这样:

user_id touchpoint_number   days_difference
1       1                   5
1       2                   20
1       3                   25
1       4                   10
2       1                   2
2       2                   30
2       3                   4

我想再创建一个列,它将创建days_difference的累积和,由user_id分区,但只要值达到30并从0开始计数就会重置。我一直试图这样做,但我不能要知道如何在PostgreSQL中做到这一点,因为它必须是递归的。

我希望得到的结果如下:

user_id touchpoint_number   days_difference cum_sum_upto30
1       1                   5               5
1       2                   20              25
1       3                   25              0    --- new count all over again
1       4                   10              10
2       1                   2               2
2       2                   30              0    --- new count all over again
2       3                   4               4

你有什么好主意可以做到这一点吗?

1 个答案:

答案 0 :(得分:1)

这应该做你想要的:

with cte as (
         select t.a, t.b, t.c, t.c as sumc
         from t
         where b = 1
         union all
         select t.a, t.b, t.c,
                (case when t.c + cte.sumc > 30 then 0 else t.c + cte.sumc end)
         from t join
              cte
              on t.b = cte.b + 1 and t.a = cte.a
        )
select *
from cte
order by a, b;

Here是rextester。

相关问题