我想在虚拟表中附加/更新记录。
TableA(ID,IdentifyingNumber,Included) TableB(ID,IdentifyingNumber,Included)
Records in TableA
1, 101, 0
2, 102, 1
3, 103, 1
Records in TableB
1, 201, 0
2, 202, 0
我需要在TableC
中输出两个表记录TableC(IdentifyingNumberA,IncludedA,IdentifyingNumberB,IncludedB)
Records in TableC
101, 0, 201, 0
102, 1, 202, 0
103, 1, Null, Null
这是我的第一张表
INSERT INTO @EntityListL(RowID,EntityID,IdentifyingNumberL,IncludedL)
SELECT ROW_NUMBER() OVER(ORDER BY d.EntityID DESC) AS Row,
d.EntityID,d.IdentifyingNumber,d.Included FROM @EntityList d
where d.Included = 0
ORDER BY d.IdentifyingNumber
这是我的第二张表
INSERT INTO @EntityListR(RowID,EntityID,IdentifyingNumberR,IncludedR)
SELECT ROW_NUMBER() OVER(ORDER BY d.EntityID DESC) AS Row,
d.EntityID,d.IdentifyingNumber,d.Included FROM @EntityList d
where d.Included = 1
ORDER BY d.IdentifyingNumber
我尝试使用下面的SQL语句
select A.IdentifyingNumber as IdentifyingNumberL, A.Included as IncludedL,
B.IdentifyingNumber as IdentifyingNumberR, B.Included as IncludedR from
(
select ROW_NUMBER() OVER(ORDER BY IdentifyingNumber) AS Row,
IdentifyingNumber, Included
from @EntityList where Included=0
)
A
left outer join
(
select ROW_NUMBER() OVER(ORDER BY IdentifyingNumber) AS Row,
IdentifyingNumber,Included from @EntityList where Included=1
)B
on A.Row=B.Row
请告诉我如何在SQL Server中实现。
先谢谢
答案 0 :(得分:2)
这应该可以解决问题:
select a.IdentifyingNumber, a.Included, b.IdentifyingNumber, b.Included
from #A a
left outer join #B b on a.ID = b.ID
这是一个完整的测试:
create table #A (ID int, IdentifyingNumber int ,Included int)
create table #B (ID int, IdentifyingNumber int ,Included int)
insert into #A values (1, 101, 0)
insert into #A values (2, 102, 1)
insert into #A values (3, 103, 1)
insert into #B values (1, 201, 0)
insert into #B values (2, 202, 0)
select a.IdentifyingNumber, a.Included, b.IdentifyingNumber, b.Included
from #A a left outer join #B b on a.ID = b.ID
结果:
IdentifyingNumber Included IdentifyingNumber Included
----------------- ----------- ----------------- -----------
101 0 201 0
102 1 202 0
103 1 NULL NULL
要将其放入新的临时表中,您需要区分列名:
SELECT a.IdentifyingNumber AS IdentifyingNumberA
,a.Included AS IncludedA
,b.IdentifyingNumber AS IdentifyingNumberB
,b.Included As IncludedB
INTO #C
FROM #A a
LEFT OUTER JOIN #B b ON a.ID = b.ID
答案 1 :(得分:-1)
使用此SQL ....
select A.IdentifyingNumber as IdentifyingNumberL, A.Included as IncludedL,
B.IdentifyingNumber as IdentifyingNumberR, B.Included as IncludedR from
(
select ROW_NUMBER() OVER(ORDER BY IdentifyingNumber) AS Row,
IdentifyingNumber, Included
from @EntityList where Included=0
)
A
full outer join
(
select ROW_NUMBER() OVER(ORDER BY IdentifyingNumber) AS Row,
IdentifyingNumber,Included from @EntityList where Included=1
)B
on A.Row=B.Row
该SQL在表中提供所有类型的记录。