根据条件向每一列插入 table 个值

Insert into each column of a table values based on conditions

我有 table 个这样的产品:

我想删除此 table 中的重复行并使用其他 table 中的 ID,因此我使用临时 table 仅添加要删除的 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

在得到我的临时文件 table 后,我得到了这个结果:

我想问是否有人可以帮助我根据需要将 ID 放入每一列中。

如果我没听错,您可以使用 window 函数在单个查询中提供代码转换 table,如下所示:

insert into #tmp (ProductId_ToKeep, ProductId_ToDelete)
select *
from (
    select 
        ProductId ProductId_ToDelete, 
        min(ProductId) over(partition by name) ProductId_ToKeep
    from dbo.[Product]
) t
where ProductId_ToDelete != ProductId_ToKeep

内部查询为给定的name拉出最小的ProductId;外部查询筛选应删除的记录(即其 ProductId 不是同名的最小值 ProductId)。