我遇到了一个问题。我有一个表,其中的一些行将有一个列数据复制。但是,其他列是唯一的。我所追求的是当它检测到这是第二行,并且前一行可能已经具有相同的列值时,在这种情况下,只需向该列值添加一些数字。
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在上面的例子中,前2行的列cmName有重复的值。我想要的是第二行应该有任何字符附加到它的值,以便它将成为唯一的行.eg。
cmpName cmpCode
cmp-ABC234FG Ont 252750023862545
cmp-ABC234FG Ont-2 252750057762511有什么仁慈的灵魂能帮我吗?提前感谢
发布于 2021-02-02 04:26:00
正如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值。
https://stackoverflow.com/questions/65999368
复制相似问题