Skip to content
Advertisement

SQL: Two similar queries into one query such that returns one table with two columns

I want to run two queries that are pretty similar such that the query returns one table with two columns (one column for each query ran)

Query #1:

Query #2:

Desired return:

admin administrator
groupID.1 groupID.1
groupID.3 groupID.2

Is it possible? I was able to get the expected return by doing a FULL OUTER JOIN but I read that JOINS are between two tables and this only looks at one table.

Advertisement

Answer

You could try assigning a row number first to each row of each table, then match the two table on this ranking:

A fully tested solution will be provided if you can share contents from the table tbl.

For the full outer join, three joins are needed:

  • INNER JOIN to match corresponding row numbers between the two tables
  • LEFT JOIN from table1 to table2 WHERE table2 is null to match excess rows from table1 in case this has more rows than table2
  • LEFT JOIN from table2 to table1 WHERE table1 is null to match excess rows from table2 in case this has more rows than table1

A pseudo test is done here.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement