【发布时间】:2019-12-02 22:32:52
【问题描述】:
我有一张这样的产品表:
我想删除此表中的重复行并使用其他表中的 Id,因此我使用临时表仅添加要删除的 Id 和要保留的 Id:
-- create tmp table
create table #tmp (ProductId_ToKeep int, ProductId_ToDelete int);
-- collect the Products that have a lower id with the same name in the temp table
insert into #tmp (ProductId_ToKeep)
select [ProductId]
from dbo.[Product] t1
where exists
(
select 1
from dbo.[Product] t2
where t2.name = t1.name
and t2.[ProductId] > t1.[ProductId]
);
-- collect the Products that have a higher id with the same name in the temp table
insert into #tmp (ProductId_ToDelete)
select [ProductId]
from dbo.[Product] t1
where exists
(
select 1
from dbo.[Product] t2
where t2.name = t1.name
and t2.[ProductId] < t1.[ProductId]
);
select * from #tmp
在获得临时表中的内容后,我得到了以下结果:
我在问是否有人可以帮助我根据需要将 Ids 放在每一列中。
【问题讨论】:
-
图像的超链接并不能真正帮助我们帮助您。花点时间将您的示例数据提供为
text,以便我们可以复制问题并测试解决方案。 -
您的示例数据没有任何重复的行,只有重复的
Name值。也许你可以澄清这个问题。
标签: sql sql-server tsql duplicates temp-tables