Sql-Server

重複記錄問題

  • January 19, 2012
create table #Personel
(
Ad varchar(100)
)

create table #Masa
(
MasaAdi varchar(100)
)

insert into #Personel values('deneme1')
insert into #Personel values('deneme2')
insert into #Personel values('deneme3')

insert into #Masa values('Masa1')
insert into #Masa values('masa2')
insert into #Masa values('masa3')

select Ad,MasaAdi from
(
select ROW_NUMBER() over(partition by MasaAdi order by ID,Ad ) as Sira,ID,Ad,MasaAdi
from (
select newid() as ID,Ad,MasaAdi 
from #Personel
cross join #Masa
)t
) t2 where Sira = 1 order by Ad

它正在創建如下所示的結果。

deneme1 - masa2
deneme2 - masa3
deneme1 - masa1 

好吧,它是能夠部署到不同的表兩次相同的個人。

e.g deneme1 - masa2
   deneme1 - masa1

我不想那樣做。我想做如下所示的事情。

e.g deneme1-masa2
   deneme2-masa3
   deneme3-masa1

因此,我不想將同一個人兩次部署到不同的表中。

with 
cte1 as
(
   select *, row_number() over(order by Ad) RowNumber
   from #Personel
),
cte2 as
(
   select *, row_number() over(order by newid()) RowNumber
   from #Masa
)
select cte1.Ad, cte2.MasaAdi
from cte1
   join cte2 on
       cte1.RowNumber = cte2.RowNumber

引用自:https://dba.stackexchange.com/questions/3485