使用相同的行数加入两列

时间:2009-06-08 09:43:47

标签: sql sql-server join

我想将2个表合并为一个。我想说:

表1

ID       Name
1        A
2        B
3        C

表2

ID       Name
4        D
5        E
6        F

我想制作Table3

Name1    Name2
A        D
B        E
C        F

如何在SQL Server中执行此操作?非常感谢任何帮助。

2 个答案:

答案 0 :(得分:5)

WITH    t1 AS
        (
        SELECT  a.*, ROW_NUMBER() OVER (ORDER BY id) AS rn
        FROM    table1 a
        ),
        t2 AS
        (
        SELECT  a.*, ROW_NUMBER() OVER (ORDER BY id) AS rn
        FROM    table2 a
        )
SELECT  t1.name, t2.name
FROM    t1
JOIN    t2
ON      t1.rn = t2.rn

答案 1 :(得分:1)

select t1.Name Name1, t2.Name Name2
from Table1 t1, table2 t2
where t1.ID = t2.ID

OR

select t1.Name Name1, t2.Name Name2
from Table1 t1 join table2 t2
     on t1.ID = t2.ID