【发布时间】: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