【问题标题】:How to calculate balance in accounting using postgres with join table如何使用带有连接表的 postgres 计算会计余额
【发布时间】:2020-11-26 03:30:20
【问题描述】:

我遇到了与此 calculate balance in 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

我知道这是一个糟糕的表格设计,但有可能达到那种结果吗? 这要怎么做?

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

【问题讨论】:

  • 请说明deduct_idcreated_time 的角色,展示您尝试过的内容,并公开您的Postgres 版本。
  • 更新了@ErwinBrandstetter 我想使用 created_time 来过滤 WHERE 条件。所以我可以在特定月份范围内获得余额,起始余额是上个月的最后余额

标签: sql database postgresql sum window-functions


【解决方案1】:

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

【讨论】:

  • 嗨,谢谢你的回答帮助我。但如果你不介意,你如何在查询中使用 WHERE created_time ?所以我可以按日期过滤,起始金额是上个月的最后余额? @GMB
猜你喜欢
  • 2014-09-26
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
  • 2012-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多