如何使用postgres窗口功能在会计软件中计算余额

编程入门 行业动态 更新时间:2024-10-24 08:30:06
本文介绍了如何使用postgres窗口功能在会计软件中计算余额的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

如何最好地处理余额计算。有人告诉我postgres中有window函数,如何使用postgres window函数来完成呢?

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

谢谢。

推荐答案

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

提琴: sqlfiddle/#!15/97dc5/2/0

请考虑更改列名 In / 输出,因此您无需将其放在引号中。 (它们是保留字)

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

如果您只想要一位客户(customer_id = 2):

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

更多推荐

如何使用postgres窗口功能在会计软件中计算余额

本文发布于:2023-10-24 16:55:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524495.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:余额   如何使用   窗口   功能   会计

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!