Mike S
Mike S

Reputation: 1613

Adding columns from SELECT queries next to each other

I have to queries that return the following tables:

foo | bar
----+----
  1 |   2
  5 |   6

and

baz | qux
----+----
  3 |   4
  7 |   8

I want to combine them to return the following table

foo | bar | baz | qux
----+-----+-----+----
  1 |   2 |   3 |   4
  5 |   6 |   7 |   8

There's no condition on which they join other than the order they're in after their individual SELECT statements. This is probably a comically easy problem, but I can't seem to figure out how to word the search to return me what I want

Upvotes: 0

Views: 50

Answers (1)

Ilya Konyukhov
Ilya Konyukhov

Reputation: 2791

You can add that condition and join those results using row_number() function:

SELECT T1.foo, T1.bar, T2.baz, T2.qux
FROM 
  (SELECT table1.*, row_number() OVER () as rnum1 FROM (query1) table1) T1
  JOIN (SELECT table2.*, row_number() OVER () as rnum2 FROM (query2) table2) T2
    ON T1.rnum1 = t2.rnum2

Depending on your situation, there can be LEFT JOIN or RIGHT JOIN instead.

Upvotes: 1

Related Questions