我有一个具有以下结构的表
我想根据类型根据time_stamp的差异更新我的持续时间列。我希望桌子看起来像这样
使用Postgres版本11。我想每隔几分钟运行一次查询以更新我的持续时间
答案 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;