简体   繁体   中英

Join two tables into one by adding data of all tables sequentially

I am facing an issue in joining three tables with different data. Suppose I am having table1 and table2 like :

table1 :     table2:
ID1         ID2
-----        ----- 
1            102
2            103

I need to join these two tables into table3 as :

table3
------
ID1    ID2
---    ---
1      102
2      103

I am applying cross join in table1 and table2 but i am gettng:

table3 :
ID1   ID2
---   ---
1     102
2     102
1     103 
2     103

If you are simply ordering by ID for each table, and then matching the first row with the first row - the following should work.

Select T1.ID1
     , T2.ID2
from (Select ID1, row_number() over (order by ID1) rownum from Table1) T1
inner join (Select ID2, row_number() over (order by ID2) rownum from Table2) T2
    on T1.rownum = T2.rownum

It create a subquery for each table with a row number, and then inner joins on the row number.

If your ID 's are not always in sequential form then use this:

SELECT t1.ID1, T2.ID2
FROM (SELECT ID1, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) rn FROM table1 ) t1
INNER JOIN (SELECT ID2, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) rn FROM table2) t2
    ON t1.rn = t2.rn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM