【问题标题】:Insert into each column of a table values based on conditions根据条件插入表值的每一列
【发布时间】: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


【解决方案1】:

如果我没听错的话,您可以使用窗口函数在单个查询中提供转码表,如下所示:

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)。

【讨论】:

  • 谢谢!我不明白这个想法,在我的情况下,我将通过最大功能更改最小值,我得到了我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
  • 1970-01-01
  • 1970-01-01
  • 2021-04-06
  • 2023-04-06
  • 2018-11-30
  • 1970-01-01
相关资源
最近更新 更多