【问题标题】:Update table based on time difference between consecutive rows根据连续行之间的时间差更新表
【发布时间】:2019-10-03 19:50:09
【问题描述】:

我有一个结构如下的表

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

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

【问题讨论】:

标签: sql postgresql date


【解决方案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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2023-02-26
    • 2017-02-14
    • 1970-01-01
    • 2019-05-29
    • 1970-01-01
    相关资源
    最近更新 更多