How join two tables using SQL without a common column

You can use ROW_NUMBER window function to create a calculated field that can be used to join the two tables together:

SELECT t1.Column1, t1.Column2, t2.Column3, t2.Column4
FROM (
   SELECT Column1, Column2,
          ROW_NUMBER() OVER (ORDER BY Column1) AS rn
   FROM Table1) AS t1
FULL OUTER JOIN  (
   SELECT Column3, Column4,
          ROW_NUMBER() OVER (ORDER BY Column3) AS rn
   FROM Table2) AS t2
ON t1.rn = t2.rn

A FULL OUTER JOIN is necessary in case either Table1 or Table2 has more rows.


Alternatively, you could also do a left join instead of full outer join:

SELECT Column1
    ,Column2
    ,t.Column3
    ,t.Column4
FROM (
    SELECT ROW_NUMBER() OVER (
            ORDER BY Column1
            ) rn
        ,Table1.*
    FROM Table1
    ) t1
LEFT JOIN (
    SELECT ROW_NUMBER() OVER (
            ORDER BY Column3
            ) AS rn
        ,t2.*
    FROM Table2 t2
    ) t ON t1.rn = t.rn;

SQL Fiddle Demo

Note: Ofcourse, this is only going to work if you have more records in TableA.


This would work:-

SELECT Column1, Column2, Column3, Column4 FROM 
(SELECT ROW_NUMBER() OVER(ORDER BY Column1) row, Table1.*
FROM Table1) t1
FULL OUTER JOIN (SELECT ROW_NUMBER() OVER(ORDER BY Column3) row, Table2.*
           FROM Table2) t2
ON t1.row = t2.row

SQLFIDDLE

Tags:

Sql Server