gpt4 book ai didi

sql - 通过附加数字将重复值转换为非重复值

转载 作者:行者123 更新时间:2023-12-01 16:20:35 26 4
gpt4 key购买 nike

我的数据库不区分大小写,但导入的数据来自外部区分大小写的系统。唯一索引由 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 轻松添加不区分大小写的排序规则。

关于sql - 通过附加数字将重复值转换为非重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53480806/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com