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

Meg*_*ez7 2 sql sql-server

我的数据库不区分大小写,但导入的数据来自外部区分大小写的系统.唯一索引由3列组成,但由于区分大小写问题,所有3列都不再是唯一的.

例:

+------+------+------+
| Col1 | Col2 | Col3 |
+------+------+------+
|    1 |    2 | abc  |
|    1 |    2 | aBc  |
|    1 |    2 | ABC  |
|    1 |    3 | abc  |
|    2 |    4 | abc  |
+------+------+------+
Run Code Online (Sandbox Code Playgroud)

我希望只将数字附加到Col3中的值,从而导致基于所有3列重复的索引.这与将附加到特定"abc"版本的数字无关.预期结果:

+------+------+------+
| Col1 | Col2 | Col3 |
+------+------+------+
|    1 |    2 | abc1 |
|    1 |    2 | aBc2 |
|    1 |    2 | ABC3 |
|    1 |    3 | abc  |
|    2 |    4 | abc  |
+------+------+------+
Run Code Online (Sandbox Code Playgroud)

可以接受这两种解决方案:更新源表或"即时"选择.

我在本地使用SQL Server 2017,在生产中使用Azure SQL.

Gor*_*off 6

你可以使用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;
Run Code Online (Sandbox Code Playgroud)

您可以轻松将其转换为更新:

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;
Run Code Online (Sandbox Code Playgroud)

COLLATE如果不是默认值,则可以使用(如果不是)来轻松添加不区分大小写的排序规则.