【问题标题】:PostgreSQL new Row based on previous Record Result基于先前记录结果的 PostgreSQL 新行
【发布时间】:2020-12-15 09:22:21
【问题描述】:

是否可以使用此表从查询中创建一个新字段ballance在底部查看预期结果)?

检查: https://dbfiddle.uk/?rdbms=postgres_12&fiddle=8ed42ebefc7390b152d293ec1176f7c0

Transaction

id      Usage         take  give 
------  ------------  ----  ----  
  1     Selling AAA   10    0         
  2     Purchase 1    0     40    
  3     Selling BBB   50    0     

所以第一条记录的余额是ballance = take(10) - give(0) = 10

第二条记录的余额是ballance = 1st record ballance(10) + take(0) - give(40) = -30

第三条记录的余额是,ballance = 2nd record ballance(-30) + take(50) - give(0) = 20

预期输出id排序:

id      Usage         take  give  ballance
------  ------------  ----  ----  --------
  1     Selling AAA   10    0     10    
  2     Purchase 1    0     40    -30
  3     Selling BBB   50    0     20

【问题讨论】:

  • 请告诉我们您想要实现的目标:您想在表格中添加一个包含计算数据的列吗?也许您应该考虑视图(或物化视图)。或者使用新功能“派生列”。因此,您无需将数据存储两次,避免数据不一致。
  • 感谢您的回复,我认为@Popeye 已经按预期回答了这个问题......

标签: sql database postgresql


【解决方案1】:

可以使用SUM解析函数如下:

select t.*,
       sum(take - give) over (order by id) as balance
from transaction t

db<>fiddle

【讨论】:

  • 哇,我没想到查询会这么短...按预期工作!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-24
  • 2020-01-31
  • 2017-02-25
  • 2015-02-15
  • 2012-05-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多