更新一个时间戳列,使其按照排序的数字列成为递增时间戳序列。

huangapple go评论64阅读模式
英文:

Update a timestamp column to make a sequence of increasing timestamps along a sorted numeric column

问题

我有一个具有单调递增整数列(id)的表格。我需要更新updated_at列(时间戳),以创建过去的时间戳递增序列。确切的步长不重要,只要时间戳单调递增。

create table temp1 (
    id serial not null,
    bar varchar(35),
    updated_at timestamp
);

insert into temp1
    (bar)
    values
    ('val1'),
    ('val2'),
    ('val3')
    ;

select * from temp1;
 id | bar  | updated_at 
----+------+------------
  1 | val1 | NULL
  2 | val2 | NULL
  3 | val3 | NULL
(3 rows)
英文:

I have a table with column of monotonically increasing integers (id). I need to update column updated_at (timestamp) to create an increasing series of timestamps, all in the past. The exact step does not matter, as long as the timestamps monotonically increase.

create table temp1 (
        id serial not null,
        bar varchar(35),
        updated_at timestamp
        )
;

insert into temp1
    (bar)
    values
    ('val1'),
    ('val2'),
    ('val3')
    ;

select * from temp1;
 id | bar  | updated_at 
----+------+------------
  1 | val1 | NULL
  2 | val2 | NULL
  3 | val3 | NULL
(3 rows)

答案1

得分: 0

以下是已翻译的内容:

一种简单的实现方法是使用日期/时间数学运算符。例如,这会生成一系列时间戳,其起始日期为过去3个月,每一行的时间戳相对于起始日期增加 id 秒:

update temp1
set updated_at = (now() - interval '3 months' + interval '1 second' * id)
    ;

select * from temp1;
 id | bar  |         updated_at         
----+------+----------------------------
  1 | val1 | 2023-01-06 17:49:59.644966
  2 | val2 | 2023-01-06 17:50:00.644966
  3 | val3 | 2023-01-06 17:50:01.644966
(3 rows)

参见:

英文:

An easy way to accomplish this would be to use the date/time math operators. For example, this generates a sequence of timestamps with a start date = 3 months in the past, and incrementing the timestamp in each row by id seconds compared with the start date:

update temp1
set updated_at = (now() - interval '3 months' + interval '1 second' * id)
    ;

select * from temp1;
 id | bar  |         updated_at         
----+------+----------------------------
  1 | val1 | 2023-01-06 17:49:59.644966
  2 | val2 | 2023-01-06 17:50:00.644966
  3 | val3 | 2023-01-06 17:50:01.644966
(3 rows)

See also:

huangapple
  • 本文由 发表于 2023年4月7日 02:10:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952535.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定