【问题标题】:Update duplicate values in a view to make unique更新视图中的重复值以使其唯一
【发布时间】:2021-12-17 23:24:24
【问题描述】:

我查看了以前的答案,但找不到如何更新列中具有重复值的视图并使它们唯一。

例如,我有一个包含 c1、c2、c3 列的视图,需要更新 c3 中的值以使其唯一,如下所示:

c1 c2 c3
ab - 99 bc - 45 ba - 12
df - 45 ef - 67 ba - 12
gh - 55 sh - 23 kj - 45

我需要更新 c3 列中“ba - 12”的值,通过在破折号前添加一个数字或字符使它们唯一,使“ba - 12”变为“ba1 - 12”或类似的东西

结果:

c1 c2 c3
ab - 99 bc - 45 ba1 - 12
df - 45 ef - 67 ba2 - 12
gh - 55 sh - 23 kj - 45

【问题讨论】:

  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: postgresql duplicates sql-update unique


【解决方案1】:

窗口函数row_numbercount 会有所帮助。新的c3 变为:如果窗口(partition by c3) 内的记录数为1,则c3 否则c3 用该窗口内的行号装饰。

create or replace view the_updated_view as
select c1, c2, 
    case when cnt = 1 then c3 
         else replace(c3, ' -', '.'||rn||' -') 
    end as c3
from 
(
  select *, row_number() over w rn, count(*) over w cnt
  from the_table
  window w as (partition by c3)
) t;

【讨论】:

    猜你喜欢
    • 2015-08-13
    • 2019-03-08
    • 1970-01-01
    • 2021-11-07
    • 2019-09-05
    • 2014-01-12
    • 2013-09-07
    • 2017-05-30
    相关资源
    最近更新 更多