问题描述
我有两个表 Table A
和 Table 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)