Sql 不完整数据上的完全外部联接(按id变量)
我有两个表(见下面的示例数据)。我需要在Sql 不完整数据上的完全外部联接(按id变量),sql,sql-server,Sql,Sql Server,我有两个表(见下面的示例数据)。我需要在表1中保留所有ID值,并通过顺序将表1与表2合并。棘手的是,我还必须保留table 1中的value1字段和table 2中的value2 表1: ID sequence value1 ------------------------- p1 1 5 p1 2 10 p2 1 15 p2
表1
中保留所有ID
值,并通过顺序将表1
与表2
合并。棘手的是,我还必须保留table 1
中的value1
字段和table 2
中的value2
表1
:
ID sequence value1
-------------------------
p1 1 5
p1 2 10
p2 1 15
p2 2 20
表2
:
sequence value2
-------------------------
1 10
2 20
3 30
4 40
我需要生成的表如下所示:
ID sequence value1 value2
----------------------------------
p1 1 5 10
p1 2 10 20
p1 3 - 30
p1 4 - 40
p2 1 15 10
p2 2 20 20
p2 3 - 30
p2 4 - 40
我尝试了以下sql代码,但它不会合并表1
中value1
字段中缺少的值,也不会将其与表2
中的values2
字段合并
select t1.ID, t2.sequence, t1.value1, t2.value2 from
t2 full outer join t1 on t2.sequence=t1.sequence
非常感谢您提供的任何帮助。您可以尝试以下方式:
select coalesce(t1.[id], t3.[id]),
, t2.[sequence]
, t1.[value]
, t2.[value]
from [tbl2] t2
left join [tbl1] t1 on t1.[sequence] = t2.[sequence]
left join (select distinct [id] from [tbl1]) t3 on t1.[id] is null
单向交叉连接和外部应用:
DECLARE @t1 TABLE(ID CHAR(2), S INT, V1 INT)
DECLARE @t2 TABLE(S INT, V2 INT)
INSERT INTO @t1 VALUES
('p1', 1, 5),
('p1', 2, 10),
('p2', 1, 15),
('p2', 2, 20)
INSERT INTO @t2 VALUES
(1, 10),
(2, 20),
(3, 30),
(4, 40)
SELECT c.ID, t2.S, ca.V1, t2.V2 FROM @t2 t2
CROSS JOIN (SELECT DISTINCT ID FROM @t1) c
OUTER APPLY(SELECT * FROM @t1 t1 WHERE c.ID = t1.ID AND t1.S = t2.S) ca
ORDER BY c.ID, t2.S
输出:
ID S V1 V2
p1 1 5 10
p1 2 10 20
p1 3 NULL 30
p1 4 NULL 40
p2 1 15 10
p2 2 20 20
p2 3 NULL 30
p2 4 NULL 40
鉴于此模式:
create table #table_1
(
ID varchar(8) not null ,
sequence int not null ,
value int not null ,
primary key clustered ( ID , sequence ) ,
unique nonclustered ( sequence , ID ) ,
)
create table #table_2
(
sequence int not null ,
value int not null ,
primary key clustered ( sequence ) ,
)
go
insert #table_1 values ( 'p1' , 1 , 5 )
insert #table_1 values ( 'p1' , 2 , 5 )
insert #table_1 values ( 'p2' , 1 , 15 )
insert #table_1 values ( 'p2' , 2 , 20 )
insert #table_2 values ( 1 , 10 )
insert #table_2 values ( 2 , 20 )
insert #table_2 values ( 3 , 30 )
insert #table_2 values ( 4 , 40 )
go
这会让你得到你想要的:
select ID = map.ID ,
sequence = map.sequence ,
value1 = t1.value ,
value2 = t2.value
from ( select distinct
t1.ID ,
t2.sequence
from #table_1 t1
cross join #table_2 t2
) map
left join #table_1 t1 on t1.ID = map.ID
and t1.sequence = map.sequence
join #table_2 t2 on t2.sequence = map.sequence
order by map.ID ,
map.sequence
go
制作:
ID sequence value1 value2
== ======== ====== ======
p1 1 5 10
p1 2 5 20
p1 3 - 30
p1 4 - 40
p2 1 15 10
p2 2 20 20
p2 3 - 30
p2 4 - 40