sql - 如何使用postgres窗口函数计算会计软件中的余额

标签 sql database postgresql window-functions accounting

我遇到了与此相同的问题,但我使用的是 Postgres。

Calculate balance with mysql

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

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/

相关文章:

mysql - 如何更新第三行中的列与 MySQL 中第二行中的列相同?

mysql - 检查 sql 中多行的条件并返回 true 或 false

ruby-on-rails - 预加载 : The right way to do things

mysql - 如何根据两个条件从 Ruby Sequel 表中删除行

sql - 如何在 SQL 查询中获得某些记录没有值的列

ruby-on-rails - Rails 服务器未启动,因为缺少 pg gem。已卸载 postgres,但出现相同的错误

mysql - 如何减去从表中选择的两个值

mysql - case,if/else 语句计算超出规范值直到在值范围内

SQL 通配符选择

sql - 如何在postgres中选择一列?