[英]Postgresql: update old record when the new one is inserted with time condition
所以,我有一个postgresql表,它继续追加不同项目的新记录
item period cost cost_diff
---------------------------------------------------------
bag 2019-03-15T18:15:00.000Z 100 0
shoe 2019-03-15T18:15:00.000Z 200 0
所以,当记录进来时,他们的cost_diff将为0.但是当新记录出现时
item period cost cost_diff
---------------------------------------------------------
bag 2019-03-15T18:15:00.000Z 100 0
shoe 2019-03-15T18:15:00.000Z 200 0
bag 2019-03-15T18:30:00.000Z 150 0
shoe 2019-03-15T18:45:00.000Z 300 0
旧记录的cost_diff将通过使用(新成本 - 旧成本)进行更新,但是当且仅当时间段是在0,15,30时插入数据的下一个15分钟时才会更新。 45分钟。
item period cost cost_diff
---------------------------------------------------------
bag 2019-03-15T18:15:00.000Z 100 50 (150-100)
shoe 2019-03-15T18:15:00.000Z 200 0 (no update)
bag 2019-03-15T18:30:00.000Z 150 0
shoe 2019-03-15T18:45:00.000Z 300 0
上面的表格显示了包含15分钟范围(18:15-> 18:30)的行李的较新记录,因此行周期为18:15的行将从18:30开始将cost_diff列更新为50减去18:15的费用,这将是150 - 50 = 100.虽然旧的鞋排不会更新(仍然是0),因为进入的新鞋记录不是接下来的15分钟(18:15-> 18) :45)当表格中插入18:30的鞋排等时会更新其他记录(有很多项目,不仅仅是show和bag如图所示)。
那么,我怎样才能根据这个问题创建一个查询,因为记录将继续进入这个表,这可以纯粹使用sql查询完成,还是需要使用python来帮助解决这个问题(我正在做一个etl管道其中此任务包含在转换过程中)
谢谢
您可以使用查询执行此操作。 使用lead()
:
select t.*,
(case when lead(period) over (partition by item order by period) < period + interval '15 minute'
then lead(cost) over (partition by item order by period) - cost
else 0
) as cost_diff
from t;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.