I have a table in a Postgres database with a column whose values are timestamps for a period of time in the past. How can I update the values in that column so the highest value (the most recent timestamp) is the current timestamp, keeping the same interval between the other ones? For example, if the current values are:
x
2019-05-23 10:00:00
2019-05-23 10:30:00
2019-05-23 11:45:00
and I run the query at 2020-07-16 14:45:00
, then I want the values to be updated to be:
2020-07-16 13:00:00
2020-07-16 13:30:00
2020-07-16 14:45:00
Advertisement
Answer
In order to update the timestamps in-place and without manually entering the current timestamp, the following query can be used:
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;
Subquery (or a CTE) is needed as UPDATE does not allow the use of window functions.