【问题标题】:How to rename duplicates in PostgreSQL如何在 PostgreSQL 中重命名重复项
【发布时间】:2021-07-09 23:54:57
【问题描述】:

我有一个 PostgreSQL 数据库,在一列中有多个重复名称。

例如,在“itemname”列中,有诸如:

sandwich
ginger brew
cream cheese
cream cheese
beer
gum
gum
beer
cream cheese
sandwich
nutella
beer
...

如您所见,项目名称重复,我正在寻找一种方法来更改所有重复名称,方法是在项目末尾添加数字,如下所示:

sandwich
ginger brew
cream cheese
cream cheese_2
beer
gum
gum_2
beer_2
cream cheese_3
sandwich_2
nutella
beer_3
...

有没有办法重命名多个重复的项目名称?

谢谢

【问题讨论】:

    标签: postgresql duplicates rename


    【解决方案1】:

    首先你可以找到副本:

    select *, row_number() over (partition by itemname order by itemname) rn
    from yourtable
    

    你可以像这样更新它们:

    update yourtable t
    set itemname = itemname || '_' || rn
    from (
           select *, row_number() over (partition by itemname order by itemname) rn
           from yourtable
    ) w
    where w.rn > 1
    and w.Id = t.Id
    

    【讨论】:

      猜你喜欢
      • 2016-06-28
      • 2012-09-19
      • 1970-01-01
      • 1970-01-01
      • 2018-03-04
      • 2019-08-14
      • 1970-01-01
      • 2021-04-17
      • 2013-12-23
      相关资源
      最近更新 更多