如何使用Joins或Cross应用获取数据

时间:2017-10-11 09:23:27

标签: sql sql-server tsql

我有要求

样本数据: 表A:

ID  name
1   cat
2   Dog
3   Bird

表B:

ID  name
1   aaa
1   bbb
2   ccc
2   ddd

表C:

ID  name
1   xxx
1   yyy
1   zzz
2   www

必需输出:

ID  name    name    name
1   cat aaa xxx
1   cat bbb yyy
1   cat null    zzz
2   Dog ccc www
2   Dog ddd www
3   Bird    NULL    NULL

我尝试过不同的连接

Select a.ID,a.name,b.name,c.name from @A a
full join @b b
on   a.ID = b.ID 
full join @c c
on   b.ID = c.ID 

有人能建议我采用最佳方法吗?

1 个答案:

答案 0 :(得分:5)

您可以使用窗口函数row_number按照idname增加b的顺序为每个c分配序号,然后执行他们之间的完全联接。最后,使用a表进行左连接:

with b1 as (
    select b.*, row_number() over (partition by id order by name) as rn
    from b
    ),
c1 as (
    select c.*, row_number() over (partition by id order by name) as rn
    from c
    )
select a.*, t.b_name, t.c_name
from a
left join (
    select coalesce(b1.id, c1.id) as id,
        b1.name as b_name,
        c1.name as c_name
    from b1
    full join c1 on b1.id = c1.id
        and b1.rn = c1.rn
    ) t on a.id = t.id;

这假设您需要根据ID和位置(按b列的顺序)加入表cname