postgresql查询如何将dups计数器附加到名称列

postgresql query how to append dups counter to name column

我有 table here.

考虑到length(name)=3,如何找到所有重复记录?并将 dups counter 作为后缀附加到名称后?

在屏幕截图下方, Key 6 and 7 的字符长度 > 3,当长度(名称)=3 时,Jay 出现两次,因此 Key 6 and 7 名称应该在 length(name)=3 之后有 dups counter 作为后缀。 Key 6 and 7

预计低于

我正在尝试使用下面的查询来获取重复项,但它 returns 仅重复数据而不是两者 Key 6 and 7 ,

select *, left(name,3)||rank() over(partition by left(name,3) order by key) as expected_name
 from (select key, name,rank() over(partition by left(name,3) order by key) as dups, tag
         from label where length(name)>3
      ) a 
 where dups >1

有没有办法获得两个重复行,以便我可以使用排名函数追加计数器。

将重复项计数(行号)附加到名称长度大于 3 的名称

select l.*,
Case when length(name)>3 and 
Count(*) OVER (PARTITION BY LEFT(name, 3)) > 1 
 then new_name
 else name end AS expected_name , 
new_name
from label l
left join 
(select key as key1, LEFT(name, 3) || ROW_NUMBER() OVER (PARTITION BY LEFT(name, 3)  ORDER BY key)
as new_name
from label where length(name)>3 ) name
on l.key=name.key1