SQL - 如何在不重复数据的情况下 select 区分和连接多个表
SQL - How to select distinct and join multiple tables without duplicating data
我有以下 table setup/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 所以我只得到每个 table 的不同实例。我正在尝试:
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
我真的只想要来自每个 table 的不同数据,如下所示:
3731572 2015 E HANSON 55489
3731572 406 N CUSTER 99809
有什么方法可以做到这一点吗?
谢谢!
我猜你想在 "row number" 上 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
。
我有以下 table setup/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 所以我只得到每个 table 的不同实例。我正在尝试:
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
我真的只想要来自每个 table 的不同数据,如下所示:
3731572 2015 E HANSON 55489
3731572 406 N CUSTER 99809
有什么方法可以做到这一点吗?
谢谢!
我猜你想在 "row number" 上 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
。