0

假设我的 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的行,而不是完全联接。

我做错了什么,我该如何解决这个问题?此外,有没有更好的方法来获得这种记录集而不是将表加入到自身上并仅更改日期参数?

谢谢!!!

4

1 回答 1

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
于 2013-08-28T18:35:15.610 回答