[英]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像:
table1 : table2:
ID1 ID2
----- -----
1 102
2 103
I need to join these two tables into table3 as : 我需要将这两个表加入到table3中:
table3
------
ID1 ID2
--- ---
1 102
2 103
I am applying cross join in table1 and table2 but i am gettng: 我在表1和表2中应用交叉联接,但我正在获取:
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. 如果您只是按ID为每个表排序,然后将第一行与第一行进行匹配,则应该可以进行以下操作。
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: 如果您的
ID
并非总是按顺序排列,请使用以下命令:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.