首页 > 解决方案 > 如何在 Postgresql 中减少所有 $0 之前创建行?

问题描述

我有以下数据:

client_id 余额月 平衡
100000000 2021-09-01 12:00 400 美元
100000000 2021-08-01 12:00 -100 美元
100000000 2021-07-01 12:00 400 美元
100000000 2021-06-01 12:00 300 美元
200000000 2021-09-01 12:00 -$500
200000000 2021-08-01 12:00 100 美元
200000000 2021-07-01 12:00 100 美元
200000000 2021-06-01 12:00 100 美元

使负余额月份之前的所有前几个月的最有效方法是什么是 0 美元,这样:

client_id 余额月 平衡
100000000 2021-09-01 12:00 400 美元
100000000 2021-08-01 12:00 -100 美元
100000000 2021-07-01 12:00 $0
100000000 2021-06-01 12:00 $0
200000000 2021-09-01 12:00 -$500
200000000 2021-08-01 12:00 $0
200000000 2021-07-01 12:00 $0
200000000 2021-06-01 12:00 $0

在 2021 年 6 月之后的历史上可能还有几个月的时间,因此我需要避免必须为每个先前的行号提供案例陈述(需要自动化)。

标签: sqlpostgresql

解决方案


嗯。. . 作为查询,您希望将最近的负平衡之前的所有行的值设置为零。一种方法是:

select t.*,
       (case when balance_month < max(balance_month) filter (where balance < 0) over (partition by client_id)
             then 0 else balance
        end) as new_balance
from t;

作为更新:

update t
    set balance = 0
    where balance_month < (select max(t2.balance_month)
                           from t t2
                           where t2.client_id = t.client_id and
                                 t2.balance < 0
                          );

推荐阅读