I have a table like this:
id col1 col2
----------- ---- -----------
1 A 5
2 A 6
3 B 5
4 B
try the following using cursor:
create table #final (id int, col1 varchar(10), col2 int)
declare @id int, @col1 varchar(10), @col2 int
declare cur cursor for select id, col1, col2 from #t order by newid()
open cur
fetch next from cur into @id, @col1, @col2
while @@FETCH_STATUS = 0
begin
if (@col1 in (select col1 from #final) or @col2 in (select col2 from #final))
begin
fetch next from cur into @id, @col1, @col2
continue
end
insert into #final
select id, @col1, @col2 from #t where col1 = @col1 and col2 = @col2 and id = @id
fetch next from cur into @id, @col1, @col2
end
close cur
deallocate cur
select * from #final order by id
drop table #final
Result: