繁体   English   中英

PostgreSQL 基于先前记录结果的新行

[英]PostgreSQL new Row based on previous Record Result

是否可以使用此表从查询中创建一个新的字段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

第 3 条记录的平衡是, ballance = 2nd record ballance(-30) + take(50) - give(0) = 20

Output 预计id订购:

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

您可以使用SUM分析 function 如下:

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

db<>小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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