SQL JOIN或UNION还是什么?

时间:2014-12-04 10:58:26

标签: sql sql-server join union

我有3个名为A,B和C的表。表A有a列。表B列a,b。表C列a,c。这些表包含如下数据:

enter image description here

我想从A,B,C获取所有数据,其中a = 1

我想要的输出应如下所示:

enter image description here

但我从SSMS获得的结果如下:

enter image description here

我应该如何重构SQL以获得所需的输出?

e.g。我不希望列中的重复值

1 个答案:

答案 0 :(得分:2)

您需要加入这些值,但不仅要加在a值,还要加在位置上。 SQL表表示无序集。我将假设bc列代表排序。

select a.a, b.b, c.c
from (select a.*, row_number() over (order by a) as seqnum
      from a
     ) a full outer join
     (select b.*, row_number() over (partition by a order by b) as seqnum
      from b
     ) b
     on a.a = b.a and a.seqnum = b.seqnum full outer join
     (select c.*, row_number() over (partition by a order by c) as seqnum
      from c
     ) c
     on c.a = coalesce(a.a, b.a) and c.seqnum = coalesce(a.seqnum, b.seqnum)
where coalesce(a.a, b.a, c.a) = 1;