[英]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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.