简体   繁体   中英

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

I'ved got a problem same as this but I am using Postgres.

Calculate balance with mysql

have a table which contains the following data:

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     

Now I need a query which gives me the following result:

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

How best to handle "balance" calculation. I was told there is window function in postgres, how would this be done using postgres window functions ?

Thanks.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM