SELECT rows with unique values in two columns

前端 未结 4 1729
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-22 08:48

I have a table like this:

id          col1 col2        
----------- ---- ----------- 
1           A    5
2           A    6
3           B    5
4           B          


        
4条回答
  •  不知归路
    2020-12-22 09:12

    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:

提交回复
热议问题