[英]Convert duplicated values to non-duplicated by appending a number
我的数据库不区分大小写,但是导入的数据来自外部区分大小写的系统。 唯一索引由3列组成,但是由于区分大小写的问题,所有3列都不再是唯一的。
例:
+------+------+------+
| Col1 | Col2 | Col3 |
+------+------+------+
| 1 | 2 | abc |
| 1 | 2 | aBc |
| 1 | 2 | ABC |
| 1 | 3 | abc |
| 2 | 4 | abc |
+------+------+------+
我希望仅将一个数字附加到Col3中的值上,从而导致基于重复的所有3列的索引。 无关紧要的是,将哪个数字附加到特定的“ abc”版本。 预期结果:
+------+------+------+
| Col1 | Col2 | Col3 |
+------+------+------+
| 1 | 2 | abc1 |
| 1 | 2 | aBc2 |
| 1 | 2 | ABC3 |
| 1 | 3 | abc |
| 2 | 4 | abc |
+------+------+------+
两种解决方案都可以接受:更新源表或“即时”选择。
我正在本地使用SQL Server 2017和生产中使用Azure SQL。
您可以使用row_number()
进行此操作。 以下假设不区分大小写的排序规则(默认)
select t.col1, t.col2,
(case when count(*) over (partition by col1, col2, col3) = 1
then col1
else col3 + convert(varchar(255), row_number() over (partition by col1, col2, col3 order by col1) )
end) as new_col3
from t;
您可以轻松地将其转换为更新:
with toupdate as (
select t.*,
(case when count(*) over (partition by col1, col2, col3) = 1
then col1
else col3 + convert(varchar(255), row_number() over (partition by col1, col2, col3 order by col1) )
end) as new_col3
from t
)
update toupdate
set col3 = new_col3
where new_col3 <> col3;
如果不是默认值,则可以使用COLLATE
轻松添加不区分大小写的排序COLLATE
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.