[英]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.