how to calculate balances in an accounting software using postgres window function

[亡魂溺海] 提交于 2019-12-01 12:42:11
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

Consider changing your column names "In" / "Out" so that you don't need to put them in quotes. (They are reserved words)

If you wanted only one customer (customer_id = 2):

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

If your query were to span multiple customers and you wanted a running balance that RESTARTED with each customer, you could use:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!