合并SQL Server中第三个表中两个表的差异

时间:2016-02-24 11:30:19

标签: sql sql-server

我有Table1和Table2这样的数据
enter image description here

enter image description here

重新突出显示,$length中有一个额外的数据字段。我想要一张这样的结果表 enter image description here

因为三个突出显示的区域显示如果表中的任何一个表中没有某些内容,那么它将在结果表中显示为null。
我尝试了使用Table2的不同解决方案不同except但不起作用。请提出一些解决方案。谢谢

2 个答案:

答案 0 :(得分:5)

您可以使用FULL OUTER JOIN

来完成
SELECT COALESCE(t1.[Date], t2.[Date]),
       CASE 
          WHEN t1.[Group] IS NULL OR t2.[Group] IS NULL THEN NULL
          ELSE t1.[Group]
       END
FROM Table1 AS t1
FULL OUTER JOIN Table2 AS t2 
  ON t1.[date] = t2.[date] AND t1.[Group] = t2.[Group]

答案 1 :(得分:0)

全外连接就是答案,另外我会添加第三列,显示哪个表有数据。

select isnull(t1.[Date],t2.[Date]) [Date],
       isnull(t1.[Group], t2.[Group])   [Group],
       case 
            when t1.[Date] is null then 'Only on table 2'
            when t2.[Date] is null then 'Only on table 1'
            else 'On both tables'
        end 
from table1 as t1
full outer join Table2 as t2 
    on t1.[Date] = t2.[Date] AND t1.[Group] = t2.[Group]