如何在Microsoft SQL Server中合并这3个表

时间:2018-08-23 15:37:48

标签: sql sql-server

我有三个表:

表1:

pk  c1 
-------
1   1
2   1 
3   1

表2:

   pk   c2 
  ---------
    3   1
    4   1 
    5   1

表3:

   pk   c3 
  ---------
    6   1
    7   1 
    8   1

我如何追加或合并这三个表,使其看起来像这张表?

    pk  c1  c2 c3
   ---------------
    1   1   0   0
    2   1   0   0
    3   1   0   0
    4   0   1   0 
    5   0   1   0 
    6   0   1   0 
    7   0   0   1
    8   0   0   1 
    9   0   0   1

当我现在使用union语句时,SQL Server会弹出两列。

select * from #table1 
union 
select * from #table2
union
select * from #table3

3 个答案:

答案 0 :(得分:2)

只需为不在每个表中的列提供0值:

select pk, c1, 0 as c2, 0 as c3
from t1
union all
select pk, 0 as c1, c2, 0 as c3
from t1
union all
select pk, 0 as c1, 0 as c2, c3
from t1;

答案 1 :(得分:0)

您需要full join

 SELECT DISTINCT
        COALESCE(t1.pk, t2.pk, t3.pk) AS pk, 
        COALESCE(t1.c1, 0) AS c1,
        COALESCE(t1.c2, 0) AS c2,
        COALESCE(t1.c3, 0) AS c3
 FROM t1 FULL OUTER JOIN 
      t2
      ON t1.pk = t2.pk FULL OUTER JOIN 
      t3
      ON t2.pk = t3.pk;

答案 2 :(得分:0)

这可能有用吗?

    select COALESCE(t1.pk,t2.pk,t3.pk) AS pk, 
           COALESCE(t1.c1, 0) AS c1,
           COALESCE(t1.c2, 0) AS c2,
           COALESCE(t1.c3, 0) AS c3
    from t1 
    full 
   outer
    join t2
      on 1 = 2
    full 
   outer
    join t3
      on 1 = 2;