2014-06-23 112 views
1

我有兩個表,我想合併的數據在一個表中它是如何可能 我的數據是這個樣子,合併排在SQL Server中兩個列

 table1 (col1 is column name)     

    col1  
    ------------------    
    data1      
    data2     
    data3    
    data4 
    data5 


    table2 (col1 is column name) 

    col1 
    ----------------------- 
    data5 
    data6 
    data7 


    expected Result 
    col1 and col2 are my columns 


    col1   col2 
    -------------------------- 
    data1   data5 
    data2   data6 
    data3   data7 
    data4 
    data5 
+0

SQL JOIN將是我的第一個猜測... – johnyTee

回答

3

您可以通過添加一個做到這一點使用row_number()join鍵:

select t1.col1, t2.col1 as col2 
from (select col1, row_number() over (order by (select NULL)) as seqnum 
     from table1 
    ) t1 full outer join 
    (select col1, row_number() over (order by (select NULL)) as seqnum 
     from table2 
    ) t2 
    on t1.seqnum = t2.seqnum; 

注:排序爲兩列,不能保證是相同的例子。您需要一列來指定排序。如果你只有一列,那麼情況就不會如此。但是,這將產生你問題中的兩列。

0
select t1.col1,t2.col as'col2' from table1 t1,table2 t2 
2
SELECT col1, col2 
FROM (
     SELECT col1, ROW_NUMBER() OVER (ORDER BY col1) rn FROM table1 
) a 
FULL OUTER JOIN (
     SELECT col1 col2, ROW_NUMBER() OVER (ORDER BY col1) rn FROM table2 
) b 
    ON a.rn = b.rn 
ORDER BY COALESCE(a.rn, b.rn); 

這裏 - 缺乏任何其他種類的標準 - 我通過自己的價值排序的列。如果您有其他排序標準,則必須更改OVER()中的ORDER BY子句以反映該情況。連接鍵是通過指定順序使用ROW_NUMBER()動態生成的。

An SQLfiddle to test with