在SQL Server中组合两个表

时间:2012-06-15 15:40:47

标签: sql-server

我有两个行数相同的表

示例:

表格a:

1,A
2,B
3,C

表格b:

AA,BB
AAA,BBB,
AAAA,BBBB

我想在SQL SErver中创建一个新表:

1,A,AA,BB
2,B,AAA,BBB
3,C,AAAA,BBBB

我该怎么做?

3 个答案:

答案 0 :(得分:1)

在SQL Server 2005 (或更新版本)中,您可以使用以下内容:

-- test data setup
DECLARE @tablea TABLE (ID INT, Val CHAR(1))
INSERT INTO @tablea VALUES(1, 'A'), (2, 'B'), (3, 'C')

DECLARE @tableb TABLE (Val1 VARCHAR(10), Val2 VARCHAR(10))
INSERT INTO @tableb VALUES('AA', 'BB'),('AAA', 'BBB'), ('AAAA', 'BBBB')

-- define CTE for table A - sort by "ID" (I just assumed this - adapt if needed)
;WITH DataFromTableA AS
(
    SELECT ID, Val, ROW_NUMBER() OVER(ORDER BY ID) AS RN
    FROM @tablea
), 
-- define CTE for table B - sort by "Val1" (I just assumed this - adapt if needed)
DataFromTableB AS 
(
    SELECT Val1, Val2, ROW_NUMBER() OVER(ORDER BY Val1) AS RN
    FROM @tableb
)
-- create an INNER JOIN between the two CTE which just basically selected the data
-- from both tables and added a new column "RN" which gets a consecutive number for each row
SELECT
    a.ID, a.Val, b.Val1, b.Val2
FROM 
    DataFromTableA a
INNER JOIN
    DataFromTableB b ON a.RN = b.RN

这为您提供了所需的输出:

enter image description here

答案 1 :(得分:0)

您的查询很奇怪,但在Oracle中您可以这样做:

select a.*, tb.*
  from a
     , ( select rownum rn, b.* from b ) tb -- temporary b - added rn column
 where a.c1 = tb.rn -- assuming first column in a is called c1

如果没有带有数字的列,你可以做两次相同的技巧

select ta.*, tb.*
  from ( select rownum rn, a.* from a ) ta
     , ( select rownum rn, b.* from b ) tb
 where ta.rn = tb.rn

注意:请注意,这可以生成随机组合,例如

1 A AA BB
2 C A B
3 B AAA BBB

因为ta和tb中没有order by

答案 2 :(得分:0)

您可以对主键进行排名,然后加入该排名:

SELECT RANK() OVER (table1.primaryKey),
  T1.*,
  T2.*
FROM 

SELECT T1.*, T2.*
FROM
(
  SELECT RANK() OVER (table1.primaryKey) [rank], table1.* FROM table1
) AS T1
JOIN
(
  SELECT RANK() OVER (table2.primaryKey) [rank], table2.* FROM table2
) AS T2 ON T1.[rank] = T2.[rank]