sql - 如何在 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 月之后的历史上可能还有几个月的时间,因此我需要避免必须为每个先前的行号提供案例陈述(需要自动化)。
解决方案
嗯。. . 作为查询,您希望将最近的负平衡之前的所有行的值设置为零。一种方法是:
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
);
推荐阅读
- python - scipy.optimize.linprog 等式约束不满足
- c++ - 使用flag=check函数检查某酒店房间流程项目的房间状态
- swift - 斯威夫特:UIButton虽然连接不工作,但其他按钮工作
- javascript - JavaScript sort() 方法的更简单方法
- python - 不和谐机器人在哪里可以找到 ffmpeg buildpack heroku
- python - 如何使用 anaconda 安装 rdkit
- c++ - 试图结束 for 循环
- arrays - (arg)对沿每个维度排序的扁平nD数组进行排序的最快方法?
- npm - NPM 包 crypto-js 是否与加密货币或密码学有关?
- pandas - 通过 buildozer 的 Android 应用程序:需求与配方