更新在SQL Server TSQL中追加重复记录

问题描述 投票:0回答:1

我有以下查询和结果。谁能帮我如何在更新查询中使用它编写代码,以便将那些重复项重命名为ELA1 (ELA1)~1(ELA1)~2(ELA1)~3

查询

SELECT        Id, DisplayName
FROM            AbpOrganizationUnits
WHERE        (TenantId = 1) AND (DisplayName IN
                             (SELECT        DisplayName
                               FROM            AbpOrganizationUnits
                               WHERE        (TenantId = 1)
                               GROUP BY DisplayName
                               HAVING         (COUNT(DisplayName) > 1)))
order by DisplayName, Id

结果

Id  DisplayName
294 ELA1 (ELA1)
295 ELA1 (ELA1)
299 ELA1 (ELA1)
292 ELA2 (ELA2)
293 ELA2 (ELA2)
285 ELA3 (ELA3)
286 ELA3 (ELA3)
302 ELA4 (ELA4)
303 ELA4 (ELA4)
279 ELA5 (ELA5)
304 ELA5 (ELA5)
290 ELAK (ELAK)
291 ELAK (ELAK)
296 Math1 (Math1)
301 Math1 (Math1)
299 Math2 (Math2)
300 Math2 (Math2)
283 Math3 (Math3)
284 Math3 (Math3)
288 Math4 (Math4)
289 Math4 (Math4)
282 Math5 (Math5)
287 Math5 (Math5)
297 MathK (MathK)
298 MathK (MathK)
309 Sci1 (Sci1)
310 Sci1 (Sci1)
305 Sci2 (Sci2)
306 Sci2 (Sci2)
311 Sci3 (Sci3)
312 Sci3 (Sci3)
313 Sci4 (Sci4)
314 Sci4 (Sci4)
280 Sci5 (Sci5)
281 Sci5 (Sci5)
307 SciK (SciK)
308 SciK (SciK)
sql sql-server tsql sql-server-2017
1个回答
1
投票
使用Common Table ExpressionROW_NUMBER window function

;WITH cte AS ( SELECT id, ROW_NUMBER() OVER (PARTITION BY DisplayName ORDER BY id) rownum FROM dbo.AbpOrganizationUnits ) UPDATE dbo.AbpOrganizationUnits SET DisplayName = DisplayName + '~' + CAST(cte.rownum AS VARCHAR(25)) FROM dbo.AbpOrganizationUnits INNER JOIN cte ON cte.id = AbpOrganizationUnits.id

© www.soinside.com 2019 - 2024. All rights reserved.