如何删除一个表中的重复行并将另一表中的引用更新为剩余行?重复仅出现在名称中。 Id 列是标识列。
Example:
假设我们有两张表Doubles
and Data
.
Doubles table (
Id int,
Name varchar(50)
)
Data Table (
Id int,
DoublesId int
)
现在我在双打表中有两个条目:
Id Name
1 Foo
2 Foo
数据表中有两个条目:
ID DoublesId
1 1
2 2
最后,双打表中应该只有一项:
Id Name
1 Foo
数据表中有两个条目:
Id DoublesId
1 1
2 1
在双打表中,每个名称可以有任意数量的重复行(最多 30 行),也可以有常规的“单”行。
我还没有运行这个,但希望它应该是正确的,并且足够接近最终的解决方案,以便让您到达那里。如果您愿意,请告诉我任何错误,我会更新答案。
--updates the data table to the min ids for each name
update Data
set id = final_id
from
Data
join
Doubles
on Doubles.id = Data.id
join
(
select
name
min(id) as final_id
from Doubles
group by name
) min_ids
on min_ids.name = Doubles.name
--deletes redundant ids from the Doubles table
delete
from Doubles
where id not in
(
select
min(id) as final_id
from Doubles
group by name
)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)