更新引用重复 Sql Server 的表

问题描述

我有两个表 Table ATable B。我需要 Table A 来引用 Table B,但我首先需要删除 Table B 的重复项并让 Table A 引用新的 ID

目前我可以使用 WITH TIES 对记录进行分区,但如何确保每条记录都指向正确的引用?

示例:

Table A
姓名 RefId
项目 1 251
项目 2 251
项目 3 167
项目 4 75
Table B
姓名 RefId
报告 1 251
报告 2 251
报告 1 167
报告 1 75

预期输出

Table C
姓名 RefId
项目 1 6
项目 2 6
项目 3 5
项目 4 6

我用来对记录进行基本上分区并删除重复项的代码是:

 SELECT TOP (1) WITH TIES Name
    FROM ReportTable
    ORDER BY ROW_NUMBER() OVER(PARTITION BY Name ORDER BY Name DESC)

但这实际上并没有更新任何引用此表的记录。我还有以下代码删除重复项,但同样,我不确定如何更新引用此表的记录。

WITH cte
     AS (SELECT nmt.Name,ROW_NUMBER() OVER(PARTITION BY nmt.Name ORDER BY nmt.Name) row_num
         FROM dbo.ReportTable nmt)
     DELETE FROM cte
     WHERE row_num > 1;

解决方法

您可以先在 UPDATE 中使用 tableA,然后在 delete 中重复使用 TableB,如下所示:

update tableA A
set A.ref_id = 
     (select max(ref_id) 
        from tableB 
       where name in (select name 
                        from tableB B 
                       where B.ref_id = A.ref_id))

delete from tableB B
 where exists 
       (select 1 from tableB BB
         where BB.NAME = B.NAME
           AND BB.ref_id > B.ref_id)