我有相同行数的两个表
例子:
表一:
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
我怎么做?
我有相同行数的两个表
例子:
表一:
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
我怎么做?
在 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
这为您提供了请求的输出:
您的查询很奇怪,但在 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
如果 a 中没有带数字的列,您可以执行两次相同的技巧
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
因为order by
ta 和 tb中没有
您可以对主键进行排名,然后加入该排名:
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]