首页 > 解决方案 > 如何使用带有连接表的 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

我知道这是不好的桌子设计,但有可能达到那种结果吗?这将如何完成?

在此先感谢,任何帮助都非常感谢。

标签: sqldatabasepostgresqlsumwindow-functions

解决方案


我认为那是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 。


推荐阅读