sql - 如何使用带有连接表的 postgres 计算会计余额
问题描述
我在 postgres 中遇到了与此计算余额相同的问题,但与连接表有关。
我有表A
ID amount deduct_id created_time
1 100.00 1 2020-01-01 15:30:20
2 10.00 1 2020-01-01 15:32:20
3 30.00 1 2020-01-01 15:43:20
4 5.00 1 2020-02-02 08:30:20
5 10.00 2 2020-02-02 23:30:20
6 20.00 2 2020-02-03 10:30:20
和表 B
deduct_id amount created_time
1 100.00 2020-02-02 10:00:20
2 15.00 2020-02-03 10:00:20
现在我需要一个查询,它给我以下结果:
ID amount deduct Balance created_time
1 100.00 0.00 100.00 2020-01-01 15:30:20
2 10.00 0.00 110.00 2020-01-01 15:32:20
3 30.00 0.00 140.00 2020-01-01 15:43:20
4 5.00 0.00 145.00 2020-02-02 08:30:20
null 0.00 100.00 45.00 2020-02-02 10:00:20
5 10.00 0.00 55.00 2020-02-02 23:30:20
null 0.00 15.00 40.00 2020-02-03 10:00:20
6 20.00 0.00 60.00 2020-02-03 10:30:20
我正在使用postgres 9.6
deduct_id用于指示数据是否是该日期扣除的一部分。
created_time表示时间线。
[更新]又如何实现按月过滤?
ID amount deduct Balance created_time
1 100.00 0.00 100.00 2020-01-01 15:30:20
2 10.00 0.00 110.00 2020-01-01 15:32:20
3 30.00 0.00 140.00 2020-01-01 15:43:20
ID amount deduct Balance created_time
4 5.00 0.00 145.00 2020-02-02 08:30:20
null 0.00 100.00 45.00 2020-02-02 10:00:20
5 10.00 0.00 55.00 2020-02-02 23:30:20
null 0.00 15.00 40.00 2020-02-03 10:00:20
6 20.00 0.00 60.00 2020-02-03 10:30:20
我知道这是不好的桌子设计,但有可能达到那种结果吗?这将如何完成?
在此先感谢,任何帮助都非常感谢。
解决方案
我认为那是union all
一个窗口sum()
:
select
id,
amount,
deduct,
sum(amount - deduct) over(order by created_time) balance,
created_time
from (
select id, amount, 0 as deduct, created_time from tablea
union all
select null, 0 as amount, amount as deduct, created_time from tableb
) t
我不清楚deduct_id
应该使用什么列。从查询的结果来看,您似乎不想使用它来定义分区,这与我所想的相反 - 所以我只是从查询中删除了 if 。
推荐阅读
- opengl - 如何对 Renderbuffer 深度信息进行采样并在 CPU 代码中进行处理,而不会对性能造成影响?
- python - 在自定义模型中,keras.layers.Embedding Output Shape 是多个
- date - ListView 中的倒计时 (Flutter)
- python - 如何在 numpy python 中创建螺旋矩阵?
- javascript - 如何在 UI Kitten v5 选择中传递动态数组?
- bash - 仅同步某些文件扩展名并在单独的 git 分支之间排除其他文件扩展名的最佳方法是什么?
- python - Tkinter - 从循环中创建的按钮中检索文本
- nginx - 如何在 nginx 中上游化请求之前在 LUA 代码中设置 proxy_http_version
- c - 三元运算符中的字符测试函数
- c++ - 如何使用 Direct2D 从 BITMAPINFOHEADER 和 BYTE 渲染位图