--测试数据ta为源数据, tb为目标数据
create table ta(id int, name varchar(10), 
value int, groupid int)
create table tb(id int, name varchar(10), 
value int, groupid int)
insert ta select 4,'A',4, 2 union all select 6,'D',6,2
union all select 7,'E',7, 2
insert tb select 1,'A',1, 1 union all select 2,'B',2,1 
union all select 3,'C',3, 1 union all select 4,'A',4,2
union all select 5,'B',5, 2
--主要部分
--注意源数据中,也要记得排除重复记录
insert tb 
select *
from ta as t1
where not exists(select 1 from tb 
    where tb.name=t1.name and tb.groupid=t1.groupid)
and exists(select top 1 id from ta 
    where name=t1.name and groupid=t1.groupid
    and id=t1.id)select * from tb
--清除
drop table ta
drop table tb

解决方案 »

  1.   

    下面的方法应该快一些insert tb
    select *  from ta
    where id in(select min(ta.id) 
        from ta left join tb
        on ta.name=tb.name and ta.groupid=tb.groupid
        where tb.id is null
        group by ta.name, ta.groupid)
      

  2.   

    insert tb select * from (select * from ta union select * from tb) A where ID not in(select ID from tb)
      

  3.   

    insert tb select * from ta union select * from tb where id not in (select id from ta )
      

  4.   

    insert into tb
    select * from ta  a 
    where not exists (select 1 from tb where id=a.id and GroupId=a.GroupId )
      

  5.   

    delete from tableName
    where id not in 
    (
      select min(id) from tableName group by datavar
    )