So you want the values from Q1 in the first two columns. Then the values from Q2 in the next two? And there's no common join column except ID?
Sounds like you want to do the pivot then!
1. Assign a row_number to each query and an identifier for each query (e.g. 'Q1', 'Q2')
2. Then union all them together
3. Finally pivot the results by:
- Taking the min of r_ref and r_amnt
- For the values of query of the identifier you created in 1.
This gives:
with q1 as (
select 10 id, 'ABC' r_ref, 123 r_amnt from dual
union all
select 10, 'BCD', 234 from dual
), q2 as (
select 10 id, 'CDE' p_ref, 345 p_amnt from dual
union all
select 10,'DEF', 456 from dual
union all
select 10, 'EFG', 567 from dual
), unions as (
select 'Q1' q, q1.*, row_number() over (order by r_ref) rn
from q1
union all
select 'Q2', q2.*, row_number() over (order by p_ref) rn
from q2
)
select * from unions
pivot (
min(r_ref) r_ref, min(r_amnt) r_amnt for q in ('Q1' q1, 'Q2' q2)
)
order by rn;
ID RN Q1_R_REF Q1_R_AMNT Q2_R_REF Q2_R_AMNT
10 1 ABC 123 CDE 345
10 2 BCD 234 DEF 456
10 3 EFG 567
You need the rownum to stop Oracle collapsing the results into a single row. Without this, you get one row with the minimums:
with q1 as (
select 10 id, 'ABC' r_ref, 123 r_amnt from dual
union all
select 10, 'BCD', 234 from dual
), q2 as (
select 10 id, 'CDE' p_ref, 345 p_amnt from dual
union all
select 10,'DEF', 456 from dual
union all
select 10, 'EFG', 567 from dual
), unions as (
select 'Q1' q, q1.*
from q1
union all
select 'Q2', q2.*
from q2
)
select * from unions
pivot (
min(r_ref) r_ref, min(r_amnt) r_amnt for q in ('Q1' q1, 'Q2' q2)
);
ID Q1_R_REF Q1_R_AMNT Q2_R_REF Q2_R_AMNT
10 ABC 123 CDE 345
If you want to know more about pivoting, read:
https://blogs.oracle.com/sql/entry/how_to_convert_rows_to