如何合并两个表?

时间:2017-04-11 08:48:14

标签: sql sql-server

示例数据:

 TableA  Table B

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

预期结果:

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

2 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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