【问题标题】:Get each month balance with capping on redshift通过红移上限获取每个月的余额
【发布时间】:2021-08-14 12:56:36
【问题描述】:

我想获取这些记录的每个月余额,每个月初的上限为 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
)

我想看看这些结果:

有什么想法吗?谢谢!

【问题讨论】:

  • 您是在问如何“限制”一个值(例如使用LEAST()),还是您是在问如何引用前行的值(例如使用窗口函数)?
  • 我认为更多的是如何引用前行的值。我需要知道之前的余额,添加新的积分,并将其限制为 500。
  • 谢谢,看起来很有用,但我认为这对我的用例来说还不够,因为我的上一行也需要基于其上一行,依此类推..

标签: sql amazon-redshift recursive-query balance rolling-sum


【解决方案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 关键字。

here 是一个使用 Postgres 的数据库小提琴。

【讨论】:

  • 它的工作!惊人的 !谢谢 !我只需要在第一句中添加列:with recursive cte(month_nb, customer_id, new_credits, debit,starting_balance) as (
猜你喜欢
  • 1970-01-01
  • 2023-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 1970-01-01
  • 2017-03-25
  • 1970-01-01
相关资源
最近更新 更多