首页 > 解决方案 > 如果发现更新第二行中的重复值

问题描述

我遇到了一个问题。我有一个表,其中某些行将重复一列数据。但是其他列是唯一的。我所追求的是当它检测到这是第二行并且前一行可能已经具有相同的列值时,在这种情况下只需向该列值添加一些数字。

if object_id('tempdb..#tempt') is not null drop table #tempt;
create table #tempt(
  cmpName varchar(50),
  cmpCode varchar(50)
)
insert into #tempt select 'cmp-ABC234FG Ont','252750023862545';
insert into #tempt select 'cmp-XDDF34FG Ont','252750057762511';
insert into #tempt select 'cmp-POC624AG Ont','252750057762789';
insert into #tempt select 'cmp-ABC234FG Ont','252750057762511';

cmpName             cmpCode
cmp-ABC234FG Ont    252750023862545
cmp-ABC234FG Ont    252750057762511
cmp-POC624AG Ont    252750057762789
cmp-XDDF34FG Ont    252750057762511

在上面的示例中,int 前 2 行列 cmName 具有重复值。我所追求的是第二行应该有任何 char 附加到它的值,以便它将成为一个唯一的行。例如。

cmpName             cmpCode
cmp-ABC234FG Ont    252750023862545
cmp-ABC234FG Ont-2  252750057762511

有好心人能帮我解决这个问题吗?提前致谢

标签: sqlsql-server

解决方案


正如 astentx 所说,您需要一列来排序或决定要更新哪一行。在这个例子中,我使用了cmpCode

if object_id('tempdb..#tempt') is not null drop table #tempt;
create table #tempt(
  cmpName varchar(50),
  cmpCode varchar(50)
)
insert into #tempt select 'cmp-ABC234FG Ont','252750023862545';
insert into #tempt select 'cmp-XDDF34FG Ont','252750057762511';
insert into #tempt select 'cmp-POC624AG Ont','252750057762789';
insert into #tempt select 'cmp-ABC234FG Ont','252750057762511';

;with cte as(
select row_number() over(partition by cmpName order by cmpCode) rn,
        *
from #tempt
)

update cte
set cmpName = concat(cmpName,'-',rn)
where rn > 1

select *
from #tempt

这将考虑到可能有两个以上具有相同cmName值的记录。


推荐阅读