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

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

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

问题

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

  1. create table temp1 (
  2. id serial not null,
  3. bar varchar(35),
  4. updated_at timestamp
  5. );
  6. insert into temp1
  7. (bar)
  8. values
  9. ('val1'),
  10. ('val2'),
  11. ('val3')
  12. ;
  13. select * from temp1;
  1. id | bar | updated_at
  2. ----+------+------------
  3. 1 | val1 | NULL
  4. 2 | val2 | NULL
  5. 3 | val3 | NULL
  6. (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.

  1. create table temp1 (
  2. id serial not null,
  3. bar varchar(35),
  4. updated_at timestamp
  5. )
  6. ;
  7. insert into temp1
  8. (bar)
  9. values
  10. ('val1'),
  11. ('val2'),
  12. ('val3')
  13. ;
  14. select * from temp1;
  1. id | bar | updated_at
  2. ----+------+------------
  3. 1 | val1 | NULL
  4. 2 | val2 | NULL
  5. 3 | val3 | NULL
  6. (3 rows)

答案1

得分: 0

以下是已翻译的内容:

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

  1. update temp1
  2. set updated_at = (now() - interval '3 months' + interval '1 second' * id)
  3. ;
  4. select * from temp1;
  1. id | bar | updated_at
  2. ----+------+----------------------------
  3. 1 | val1 | 2023-01-06 17:49:59.644966
  4. 2 | val2 | 2023-01-06 17:50:00.644966
  5. 3 | val3 | 2023-01-06 17:50:01.644966
  6. (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:

  1. update temp1
  2. set updated_at = (now() - interval '3 months' + interval '1 second' * id)
  3. ;
  4. select * from temp1;
  1. id | bar | updated_at
  2. ----+------+----------------------------
  3. 1 | val1 | 2023-01-06 17:49:59.644966
  4. 2 | val2 | 2023-01-06 17:50:00.644966
  5. 3 | val3 | 2023-01-06 17:50:01.644966
  6. (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:

确定