2017-04-11 172 views
0

樣本數據:如何合併兩個表?

TableA Table B 

ID  ID2 
---- ----- 
    1  5 
    2  6 
    3  7 

預期結果:

ID ID2 
--------- 
    1 5 
    2 6 
    3 7 
+1

你到目前爲止嘗試了什麼?任何努力? –

+0

@a_horse_with_no_name SQL SERVER Bro ... –

+0

向表B添加一行,並調整結果。 – jarlh

回答

1
Begin TRAN 

CREATE TABLE #TableA(ID INT) 
CREATE TABLE #TableB (ID2 INT) 

INSERT INTO #TableA 
SELECT 1 UNION ALL 
SELECT 2 UNION ALL 
SELECT 3 

INSERT INTO #TableB 
SELECT 5 UNION ALL 
SELECT 6 UNION ALL 
SELECT 7 

Select ROW_NUMBER()OVER(ORDER BY ID)ROWNUM,ID INTO #Temp FROM #TableA 
Select ROW_NUMBER()OVER(ORDER BY ID2)ROWNUM,ID2 INTO #Temp_Data FROM #TableB 

SELECT ID,ID2 
FROM #Temp a 
INNER JOIN #Temp_Data b ON a.ROWNUM=b.ROWNUM 

ROLLBACK TRAN 
+0

好工作.... –

+0

@HartHartono歡迎兄弟 –

1

如果您正在使用SQL Server,然後CTE可以幫助你獲得渴望的結果如下

;WITH CTE1 AS(
    SELECT *, 
      ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) AS RN 
    FROM Table1 
),CTE2 AS(
    SELECT *, 
      ROW_NUMBER() OVER(PARTITION BY ID2 ORDER BY ID2) AS RN 
    FROM Table2 
)  
SELECT * 
FROM CTE1 
INNER JOIN CTE2 ON CTE1.RN=CTE2.RN