编写查询以显示以下结果?

时间:2015-06-28 12:20:45

标签: sql sql-server

共有3个表格:

表A:

code    aname
------- ---------
1       A
2       B
3       C

表B:

code        bname
----------- ----------
1           aaa
1           bbb
2           ccc
2           ddd

表C:

code        cname
----------- ----------
1           xxx
1           yyy
1           zzz
2           www

我们需要编写一个显示以下结果的查询:

code        aname      bname            cname
----------- ---------- ----------      ----------
1           A          aaa              xxx
1           A          bbb              yyy
1           A          NULL             zzz
2           B          ccc              www
2           B          ddd              NULL
3           C          NULL             NULL

2 个答案:

答案 0 :(得分:0)

您需要建立TableBTableC的排序列,因为它们的数量似乎很重要。我将使用许多系统支持的CTEs,但您可以改为子查询。

with tbb as (
  select
    *
    ,row_number() over (partition by code order by bname) nameorder
  from
    TableB
), tbc as (
  select
    *
    ,row_number() over (partition by code order by cname) nameorder
  form
    TableC
), mrg as (
  select
    coalesce(tbb.code, tbc.code) code
    ,bname
    ,cname
  from
    tbb
    full outer join tbc on
      tba.code = tbb.code
      and tba.nameorder = tbb.nameorder
)
select
  tba.code
  ,aname
  ,bname
  ,cname
from
  TableA tba
  left outer join mrg on tba.code = mrg.code

答案 1 :(得分:0)

您没有完整的join密钥,因为您需要每列中的列表。为此,您需要使用full outer join并生成订购密钥。注意:每列中的最终排序是任意的。

select coalesce(a.code, b.code, c.code) as code,
       a.aname, b.bname, c.cname
from (select a.*, row_number() over (partition by code order by code) as seqnum
      from a
     ) a full outer join
     (select b.*, row_number() over (partition by code order by code) as seqnum
      from b
     ) b
     on a.code = b.code and a.seqnum = b.seqnum full outer join
     (select c.*, row_number() over (partition by code order by code) as seqnum
      from c
     ) c
     on c.code in (a.code, b.code) and c.seqnum in (a.seqnum, b.seqnum)