将多个表合并为一个

时间:2015-12-02 09:01:27

标签: sql sql-server-2008-r2

如果我有tlb1:

col1

1

2

3

现在我将tlb2作为:

col2   col3

 4     Four  

 5     Five  

 6     SIX

不,我有tlb3

   col4          col5

    sample14     sample15

    sample24     sample25

    sample34     sample35

如果我想要结果为什么可以是查询:

col1 col2   col3   col4       col5     

1     4     Four   sample14   sample15 

2     5     Five   sample24   sample25

3     6     Six    sample34   sample35

我尝试过:

select ( (select * from tlb1), (select * from tlb2),(select * from tlb3)) T

但这失败了。

请帮帮我。

1 个答案:

答案 0 :(得分:3)

 with t1 as (select col1, row_number() over (order by col1) rn from tbl1 ),
 t2 as (select col2,col3, row_number() over (order by col2) rn from tbl2),
 t3 as (  select col4,col5, row_number() over (order by col4) rn  from tbl3) 
 select t1.col1,t2.col2,t2.col3,t3.col4,t3.col5 
 from t1 full outer join t2 on t1.rn = t2.rn
 t3 full outerjoin t2 on t2.rn = t3.rn

尝试这样的事情......