一尘不染

如何使用postgres窗口功能在会计软件中计算余额

sql

有一个包含以下数据的表:

ID      In       Out 
1      100.00    0.00   
2       10.00    0.00   
3        0.00   70.00    
4        5.00    0.00    
5        0.00   60.00   
6       20.00    0.00

现在,我需要一个查询,该查询给出以下结果:

ID      In       Out    Balance
1      100.00    0.00   100.00
2       10.00    0.00   110.00
3        0.00   70.00    40.00
4        5.00    0.00    45.00
5        0.00   60.00   -15.00
6       20.00    0.00     5.00

如何最好地处理“余额”计算。有人告诉我postgres中有window函数,如何使用postgres window函数来完成呢?

谢谢。


阅读 143

收藏
2021-03-10

共1个答案

一尘不染

select t.*, sum(“In”-“Out”) over(order by id) as balance
from tbl t
order by id

小提琴: http
**://sqlfiddle.com/#!15/97dc5/2/0**

考虑更改列名“ In” /“ Out”,这样您就不必在引号中加上引号了。(它们是保留字)

如果只需要一位客户(customer_id = 2):

select t.*, sum("In"-"Out") over(order by id) as balance
from tbl t
where customer_id = 2
order by id

如果您的查询要跨越多个客户,并且您希望与每个客户重新开始保持平衡,则可以使用:

select t.*, sum("In"-"Out") over( partition by customer_id
                                  order by customer_id, id ) as balance_by_cust
from tbl t
order by customer_id, id
2021-03-10