sql - 如果发现更新第二行中的重复值
问题描述
我遇到了一个问题。我有一个表,其中某些行将重复一列数据。但是其他列是唯一的。我所追求的是当它检测到这是第二行并且前一行可能已经具有相同的列值时,在这种情况下只需向该列值添加一些数字。
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
有好心人能帮我解决这个问题吗?提前致谢
解决方案
正如 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
值的记录。
推荐阅读
- android - Play 控制台预发布报告不适用于 Android App Bundle
- json - AJAX — 发送不带 URL 编码的 JSON
- c# - 当我尝试在单击提交按钮时将记录与图像一起保存时,它显示 GDI+ 中发生了一般错误
- awk - AWK 帮助从一行中减少一些价值
- powershell - 如何将批处理脚本if语句转换为powershell?
- typescript - 为什么不允许我声明在 typescript 中实现的函数?
- azure - 让服务主体访问 ADLS 文件的正确方法
- couchdb - 如何使用查询字符串中的输出参数作为输入?
- python - 查找所有可能的幻方(3x3)python
- java - Firebase Google 登录返回 com.google.android.gms.common.api.ApiException: 12500