3

我想获得这些记录的每个月余额,每个月初的上限为 500 个学分。

而且我有点卡住了,因为我认为我不能简单地进行滚动计算,因为客户的最大余额是他新信用额度的两倍(我在示例中使用 500 作为最大值)。

这是我的数据:

CREATE TABLE table1 as (
SELECT 'A' as customer_id, 250 as new_credits, -62 as debit, 1 as month_nb
UNION ALL
SELECT 'A', 250,    -84,    2
UNION ALL
SELECT 'A', 250,    -8, 3
UNION ALL
SELECT 'A', 210,    -400,   4
UNION ALL
SELECT 'A', 210,    -162,   5
UNION ALL
SELECT 'A', 210,    0,  6
)

我想看到这些结果:

结果

任何想法 ?谢谢 !

4

1 回答 1

1

我正在添加一个新答案,因为之前的答案已过时。我不确定 Redshift 的确切语法是什么(文档似乎没有完全更新),但这是一个想法:

with recursive cte as (
      select month_nb, customer_id, new_credits, debit, new_credits as starting_balance
      from table1
      where month_nb = 1
      union all
      select t1.month_nb, t1.customer_id, t1.new_credits, t1.debit,
             least(500, cte.starting_balance + cte.debit + t1.new_credits)
      from cte join
           table1 t1
           on t1.month_nb = cte.month_nb + 1 and t1.customer_id = cte.customer_id
     )
select *
from cte;

例如,我不确定是否recursive需要关键字。

这是一个使用 Postgresdb<>fiddle。

于 2021-05-29T18:19:53.740 回答