我使用了增量方法。我真的没有看到其他选择。我相信这会返回您需要的东西:
create table #t1
(
ID int identity,
name varchar(3),
devID int
)
insert into #t1(name,devID)
values('abc',101),('def',111),('ghi',121),('abc',102),('def',110)
create table #t2
(
ID int,
name varchar(3),
devID int
)
declare @count int = 1,
@name1 varchar(3)
while @count <= (select MAX(ID) from #t1)
begin--1
set @name1 = (select name from #t1 where ID = @count)
if (@name1 not in (select distinct name from #t2)) or ((select devID from #t1 where ID = @count) < (select devID from #t2 where name = @name1))
begin--2
insert into #t2
select *
from #t1
where ID = @count
end--2
else
begin--2
update #t2
set devID = (select devID from #t1 where ID = @count)
where name = @name1
end--2
set @count+=1
end--1
select *
from #t2
drop table #t1
drop table #t2
编辑:结果:
ID name devID
----------- ---- -----------
1 abc 102
2 def 111
3 ghi 121
5 def 110
(4 row(s) affected)