假设我在SQL Server DB中有这个表:
Date Col_A Col_B Col_C ...
Day1 1 2 3 ....
Day1 2 3 4 ....
Day1 3 4 5 ....
Day2 1 2 3 ....
Day2 2 3 4 ....
Day2 5 6 7 ....
Day2 6 7 8 ....
我希望根据Col_A
,Col_B
& Col_C
获得如下内容:
Date Col_A Col_B Col_C ... Date Col_A Col_B Col_C ....
Day1 1 2 3 .... Day2 1 2 3 ....
Day1 2 3 4 .... Day2 2 3 4 ....
Day1 3 4 5 .... NULL NULL NULL NULL ..NULL..
NULL NULL NULL NULL ..NULL.. Day2 5 6 7 ....
NULL NULL NULL NULL ..NULL.. Day2 6 7 8 ....
我认为这个SQL会这样做:
SELECT * FROM
(Select * from MyTable where Date = 'Day1') T1
FULL OUTER JOIN
(Select * from MyTable where Date = 'Day2') T2
ON
T1.Col_A = T2.Col_A
AND
T1.Col_B = T2.Col_B
AND
T1.Col_C = T2.Col_C
但这只是返回T1已满且T2有NULLS
的行,而不是完整的连接。
我做错了什么,如何解决这个问题? 另外,是否有更好的方法来获得这种记录集,而不是将表连接到自身并只更改日期参数??
感谢!!!
答案 0 :(得分:0)
你的加入看起来不错,请尝试这样的事情以确保(正确命名所有列):
select
isnull(T1.Col_A, T2.Col_A) as Col_A,
isnull(T1.Col_B, T2.Col_B) as Col_B,
isnull(T1.Col_A, T2.Col_C) as Col_C,
T1.Date as Date1,
T2.Date as Date2
from (select * from MyTable where Date = 'Day1') as T1
full outer join (select * from MyTable where Date = 'Day2') as T2 on
T1.Col_A = T2.Col_A and T1.Col_B = T2.Col_B and T1.Col_C = T2.Col_C
order by 1, 2, 3