代码之家  ›  专栏  ›  技术社区  ›  Jessica Warren

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

  •  0
  • Jessica Warren  · 技术社区  · 6 年前

    我有三张桌子:

    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
    

    我该如何附加或合并这三个表以使其看起来像一个this table??

        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
    

    select * from #table1 
    union 
    select * from #table2
    union
    select * from #table3
    
    3 回复  |  直到 6 年前
        1
  •  2
  •   Gordon Linoff    6 年前

    只需为不在每个表中的列提供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;
    
        2
  •  0
  •   Yogesh Sharma    6 年前

    你需要 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;
    
        3
  •  0
  •   Error_2646    6 年前

    这可能有用吗?

        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;