【问题标题】:Increment column value in postgresql在 postgresql 中增加列值
【发布时间】:2020-04-02 20:35:16
【问题描述】:

test_id 的数据类型是 int(4) 我正在尝试将 test_id 的值增加 1。

下面是表格

test_id   name   location

 245      Frank    CA
 245      Roy      MO
 245      Tom      KS
 245      Chris    KS
 245      Harry    MO

预期输出

  test_id   name   location

   245      Frank    CA
   246      Roy      MO
   247      Tom      KS
   248      Chris    KS
   249      Harry    MO

【问题讨论】:

  • 请告诉我们您究竟是如何“尝试”的。
  • 不可能,因为顺序是随机的

标签: sql postgresql auto-increment


【解决方案1】:

假设其他值唯一地定义每一行,您可以使用row_number()join

update t
    set test_id = test_id + seqnum
    from (select t.*, row_number() over () - 1 as seqnum
          from t
         ) tt
    where tt.name = t.name and tt.location = t.location;

您可能需要row_number()order by 以获取具有特定顺序的结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-23
    • 2019-02-07
    • 2015-03-21
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多