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

后端 未结 1 1326
我寻月下人不归
我寻月下人不归 2020-12-18 10:56

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            


        
相关标签:
1条回答
  • 2020-12-18 11:38
    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
    
    0 讨论(0)
提交回复
热议问题