Reputation: 569
Lets say I have 2 tables - Table 1 and Table 2:
I want to be able to go down the in the order that the two tables are presented in and match without duplication. So for this example:
So the results table would look something like this:
How would one do this is SQL? Is there a type of "JOIN" that would do this? Is it possible to have for-loops in SQL where you find the match from Table 2 and remove that instance from Table 2 in time for the next iteration of the loop?
Upvotes: 2
Views: 164
Reputation: 1269693
Use row numbers:
select t1.*, t2.*
from (select t1.*, row_number() over (partition by type order by id) as seqnum
from table1 t1
) t1 left join
(select t2.*, row_number() over (partition by type order by (select null)) as seqnum
from table1 t2
) t2
on t1.type = t2.type and t1.seqnum = t2.seqnum;
Note that SQL tables represent unordered sets. You have no obvious ordering in table2
, so no ordering is guaranteed in the results.
Upvotes: 2