根据连续行之间的时差更新表

时间:2019-10-03 19:50:09

标签: sql postgresql date

我有一个具有以下结构的表

enter image description here

我想根据类型根据time_stamp的差异更新我的持续时间列。我希望桌子看起来像这样

enter image description here

使用Postgres版本11。我想每隔几分钟运行一次查询以更新我的持续时间

1 个答案:

答案 0 :(得分:1)

尝试使用lead()窗口功能:

SELECT id, type, time_stamp,
       lead(time_stamp) OVER (PARTITION BY type ORDER BY time_stamp) - time_stamp
FROM atable
ORDER BY time_stamp;

如果要更新表,可以这样做:

UPDATE atable
SET timeduration = x.td
FROM (SELECT id,
             lead(time_stamp) 
                OVER (PARTITION BY type ORDER BY time_stamp)
                - time_stamp AS td
      FROM atable) AS x
WHERE x.id = atable.id AND x.td IS NOT NULL;