我遇到了与此相同的问题,但我使用的是 Postgres。
有一个包含以下数据的表:
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 中有窗口函数,如何使用 postgres 窗口函数来完成?
谢谢。
最佳答案
select t.*, sum("In"-"Out") over(order by id) as balance
from tbl t
order by id
fiddle : 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
关于sql - 如何使用postgres窗口函数计算会计软件中的余额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25110703/