SQL - 更新其他列中每个副本的列

时间:2014-01-05 18:06:26

标签: sql sql-server

我正在寻找一个SQL查询,将列更新为另一列中每个副本的相同Id,然后从另一个表中删除每个覆盖的行。

例如

我有:

IndustryId      ProductId       ExternalId
144             3332            13
147             3423            13
148             3532            13
2637            63199           32
121             2789            32

我想:

IndustryId      ProductId       ExternalId
144             3332            13
147             3332            13
148             3332            13
2637            63199           32
121             63199           32

我还需要记录覆盖的ProductId值,以便我可以删除另一个表中的那些行(3423,3532和2789应该在另一个表中删除)。如果需要,可以在多个查询中,这无关紧要。

实现这一目标的最佳方法是什么?

2 个答案:

答案 0 :(得分:1)

这不是太难,特别是如果你打破了步骤。 看看这个:

if object_id('tempdb..#myData') is not null
    drop table #myData;

create table #myData ( industryid int, productId int, externalId int);

insert into #myData (industryId, productId, externalId)
values (144,3332,13);
insert into #myData (industryId, productId, externalId)
values (147,3423,13);
insert into #myData (industryId, productId, externalId)
values (148,3532,13);
insert into #myData (industryId, productId, externalId)
values (2637,63199,32);
insert into #myData (industryId, productId, externalId)
values (121,2789,32);

                        --select * from #myData;
-------------------------------------------------
if object_id('tempdb..#IdsToKeep') is not null
    drop table #IdsToKeep;
if object_id('tempdb..#badRows') is not null
    drop table #badRows;

create table #IdsToKeep (externalId int, productId int);
create table #badRows ( industryId int, productId int, externalId int);

insert into #IdsToKeep 
select
    externalId, min(productId)
from
    #myData
group by
    externalId;


--- Capture rows that will be changed ---
insert into #badRows
select
    md.industryId, md.productId, md.externalId
from
    #myData md
        left join #IdsToKeep itk on 
                            md.externalId = itk.externalId
                            and
                            md.productId = itk.productId
where
    itk.productId IS NULL
;


--- Make the update to the main table ---
update 
    #myData
set
    productId = itk.productId
from
    #myData
        inner join #IdsToKeep itk on #myData.externalId = itk.externalId
;


----------
select * from #mydata;
select * from #badRows;

答案 1 :(得分:0)

declare @table table (IndustryId int, ProductId int, ExternalId int) insert into @table values (144,3332,13), (147,3423,13), (148,3532,13), (2637,63199,32), (121,2789,32)

select * from @table

;with cte (productid, externalid) as (select max(productid), ExternalId from @table group by ExternalId) select t.IndustryId, c.productid, c.externalid from cte c right outer join @table t on c.externalid = t.ExternalId