簡體   English   中英

SQL-如何選擇不同的表並聯接多個表而不重復數據

[英]SQL - How to select distinct and join multiple tables without duplicating data

我有以下表格設置/數據:

create table #temp (irecordid int, sdocumentno varchar(20), dtfileddate datetime, mnyconsideration money)

insert into #temp values (1, '3731572', '6-30-2014', 120.00)

Create table #temp2 (irecordid int, address varchar(255))

insert into #temp2 values (1, '406 N CUSTER')
insert into #temp2 values (1, '2015 E HANSON')


Create table #temp3 (irecordid int, srdocumentno varchar(25))
insert into #temp3 values (1, '55489')
insert into #temp3 values (1, '99809')

我試圖選擇,所以我只得到每個表的不同實例。 我在嘗試:

select distinct sdocumentno, address, srdocumentno
from #temp t1
join #temp2 t2 on t1.irecordid = t2.irecordid
join #temp3 t3 on t1.irecordid = t3.irecordid

我的結果如下:

3731572 2015 E HANSON   55489
3731572 2015 E HANSON   99809
3731572 406 N CUSTER    55489
3731572 406 N CUSTER    99809

我真的只希望像這樣來自每個表的不同數據:

3731572   2015 E HANSON   55489
3731572   406 N CUSTER   99809

有沒有辦法可以做到這一點?

謝謝!

我猜想您想join “行號”,但是那不存在。 但是,您可以生成一個,然后加入它們:

select sdocumentno, address, srdocumentno
from #temp t1 join
     (select t2.*,
             row_number() over (partition by irecordid order by (select NULL)) as seqnum
      from #temp2 t2
     ) t2
     on t1.irecordid = t2.irecordid join
     (select t3.*,
             row_number() over (partition by irecordid order by (select NULL)) as seqnum
      from #temp2 t3
     ) t3
     on t1.irecordid = t3.irecordid and t2.seqnum = t3.seqnum;

如果列表的長度不同,則可以使用full outer join聯接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM