[英]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.