Sqlserver
 sql >> Datenbank >  >> RDS >> Sqlserver

Vollständige Verknüpfung mehrerer Tabellen in denselben Spalten

Es gibt mehrere Möglichkeiten, aber ich denke, die folgende ist die beliebteste:

select allk.k, t1.c1, t2.v2, t3.v3, t4.v4
from (select k from t1 union 
      select k from t2 union
      select k from t3 union
      select k from t4
     ) allk left outer join
     t1
     on allk.k = t1.k left outer join
     t2
     on allk.k = t2.k left outer join
     t3
     on allk.k = t3.k left outer join
     t4
     on allk.k = t4.k;

Wenn Sie eine separate Tabelle aller k haben Werten können Sie diese anstelle von allk verwenden Unterabfrage.

Eine einfachere Möglichkeit, Ihren full outer join zu schreiben Abfrage ist die Verwendung von coalesce() :

SELECT COALESCE(t1.K, t2.K, t3.K, t4.K) [K], V1, V2, V3, V4
FROM @T1 t1 FULL JOIN
     @T2 t2
     ON t2.K = t1.K FULL JOIN
     @T3 t3
     ON t3.K = coalesce(t1.K, t2.K) FULL JOIN
     @T4 t4
     ON t4.K = coalesce(t1.K, t2.K, t3.k);

Und die dritte Methode ist die union all /group by Methode:

select k, max(v1) as v1, max(v2) as v2, max(v3) as v3, max(v4) as v4
from (select k, v1, NULL as v2, NULL as v3, NULL as v4
      from t1 union all
      select k, NULL as v1, v2, NULL as v3, NULL as v4
      from t2 union all
      select k, NULL as v1, NULL as v2, v3, NULL as v4
      from t3 union all
      select k, NULL as v1, NULL as v2, NULL as v3, v4
      from t4
     ) t
group by k;