views:

135

answers:

3

Hi all,

I want to combine 2 tables into one. Let say I have:

Table1

ID       Name
1        A
2        B
3        C

Table2

ID       Name
4        D
5        E
6        F

I want to make Table3

Name1    Name2
A        D
B        E
C        F

How can I do this in SQL Server? Any help is greatly appreciated.

A: 
SELECT Table1.Name as Name1, Table2.Name as Name2 
FROM Table1 
NATURAL JOIN Table2;

[Edit: If you want to actually CREATE a new table, add a INTO Table3]

yhager
+1  A: 
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
Rashmi Pandit
What if there is no column ID?
NVA
If there is no ID how are the tables related? What criteria determines Name1 = A corresponds to Name2 = D?
Rashmi Pandit
If you do not have id, use Quassnoi's solution and in the order by clauses replace id with the primary keys of your table.
Rashmi Pandit
As primary keys form the clustered index, so your row in Table1 will match tht in Table2
Rashmi Pandit
+5  A: 
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
Quassnoi
little bug: ON t1.rn = r2.rn
ammoQ
ammoQ: Um.... sure
Quassnoi