【问题标题】:Update the timestamp values in a column so that the latest timestamp is current time while maintaining the relative time difference between rows更新列中的时间戳值,使最新的时间戳是当前时间,同时保持行之间的相对时间差
【发布时间】:2020-07-16 21:50:09
【问题描述】:

我在 Postgres 数据库中有一个表,其中有一列的值是过去一段时间的时间戳。如何更新该列中的值,使最高值(最近的时间戳)是当前时间戳,保持其他时间戳之间的间隔相同?例如,如果当前值为:

2019-05-23 10:00:00
2019-05-23 10:30:00
2019-05-23 11:45:00

我在2020-07-16 14:45:00 运行查询,然后我希望将值更新为:

2020-07-16 13:00:00
2020-07-16 13:30:00
2020-07-16 14:45:00

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    你需要一些时间戳算法:

    select t.*,
           ( ts + (current_timestamp - max(ts) over ()) ) as new_ts
    from t;
    

    Here 是一个 dbfiddle。

    编辑:

    要更新,您可以使用:

    update t
        set ts =  ( ts + (current_timestamp -  max_ts) )
        from (select max(ts) as max_ts from t) tt;
    

    【讨论】:

    • 感谢您的回复。我正在寻找更新到位的时间戳,而无需手动输入当前时间戳。我实际上已经弄清楚了,我也会将其添加为将来参考的答案。
    【解决方案2】:

    为了在不手动输入当前时间戳的情况下就地更新时间戳,可以使用以下查询:

    UPDATE
       sample_metrics_data 
    SET
       "timestamp" = sub.new_ts 
    FROM
       (
          SELECT
             timestamp,
             (
                NOW() - (max(timestamp) over ()) + timestamp
             )
             AS new_ts 
          FROM
             sample_metrics_data 
       )
       sub 
    WHERE
       sample_metrics_data.timestamp = sub.timestamp;
    

    需要子查询(或 CTE),因为 UPDATE 不允许使用窗口函数。

    【讨论】:

      猜你喜欢
      • 2019-05-06
      • 2023-04-09
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-09
      • 2019-12-31
      相关资源
      最近更新 更多