2012-06-15 89 views
0

我有相同数量的行的结合两个表中的SQL Server

例丝束表:

表一:

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 

我该怎么做?

+2

sql server,sybase,oracle,mysql? –

+2

如果没有加入的价值,简单地排列每个one-for-one旁边的记录是不可能的。除非使用特定于数据库的语法。 – bluevector

+1

AA,BB如何知道它应该被附加到1,A? – mawburn

回答

1

在SQL Server (或更新版本),你可以使用这样的事情:

-- 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

+0

是的,这就是它thx –

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没有order by和tb

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]