查找重复的ID并添加新的序列ID

时间:2018-11-16 01:58:19

标签: sql duplicates sequence

我有一个表,其中ID必须是唯一的。有些ID不是唯一的。如何生成一个新列,将一个序列添加到此ID?我想在下表中生成ID_new_generation

ID Company Name ID_new_generated
1  A            1
1  B            1_2
2  C            2

3 个答案:

答案 0 :(得分:0)

假设您正在寻找SQL Server中的解决方案:

首先,您需要添加一个可空列ID_Generated,如下所示:

ALTER TABLE tablename
ADD COLUMN ID_Generated varchar(25) null
GO

然后,在cte结构中使用如下所示的row_number(如果使用mysql,则可以使用temp表):

;with cte as (
   SELECT DISTINCT t.ID,  
                   (ROW_NUMBER() over (partition by t.ID order by t.ID)) as RowNumber
   FROM tablename t
   INNER JOIN (select ID, Count(*) RecCount
               From tablename
               group by ID
               having Count(*) > 1) tt on t.ID = t.ID 
   ORDER BY id ASC
)
Update t
set t.ID_Generated = cte.RowNumber
from tablename t
inner join cte on t.ID = cte.ID

答案 1 :(得分:0)

您可以使用开窗功能(例如,等级)在具有相同ID号的行定义的每个窗口上生成辅助ID,然后将其串联以创建新的ID。

类似:

select 
    ID
    , companyName
    , rank() over(partition by ID ORDER BY companyName)
    , concat(ID, '_',  rank() over(partition by ID ORDER BY companyName)) as new_id
from test;

观看此演示:https://www.db-fiddle.com/f/bd6aQKnZ7gcZCQjFpZicrp/0

语法会有所不同,具体取决于您所使用的SQL。

答案 2 :(得分:0)

我想你想要

select ID, companyName,
       (case when row_number() over (partition by id order by companyname) = 1
             then cast(id as varchar(255))
             else id || '_'  || row_number() over (partition by id order by companyname)
        end) as new_id
from test;

||是SQL中的ANSI / ISO标准串联运算符。并非所有数据库都支持它,因此您可能需要用适合您数据库的操作符来代替该操作符。