1

I have a issuse in sql query.

I have 2 select:

The first one showing:

 columnA|columnB
   A    |2
   B    |3
   D    |5

The other one showing:

columnA|columnC
     A   |1
     B   |5
     C   |7

I'm tying to merge this tow query,

this is my query:

with 
cte1 as (
select  A,B  from table1 group by A
),
cte2 as (
   select  A,C from table2  group by A
)
select c1.A, c1.B, c2.C
from cte1 c1 left join cte2 c2 
on c2.A = c1.A
order by c1.A asc

The problem is when I'm using "Left join" the result is :

ColumnA|ColumnB|ColumnC
A      |2      |1
B      |3      |5
D      |5      |null

It's not showing the value C for the second table,

And whene I'm using "right join" the result is :

ColumnA|ColumnB|ColumnC
A      |2      |1
B      |3      |5
C      |null   |7

It's not showing the value D for the first table,

The result should be like that:

 ColumnA|ColumnB|ColumnC
    A      |2      |1
    B      |3      |5
    C      |null   |7
    D      |5      |null

any solution please

Vivek Jain
  • 2,730
  • 6
  • 12
  • 27
bfs
  • 65
  • 1
  • 7

3 Answers3

0

You are describing a full join:

with 
    cte1 as (...),
    cte2 as (...)
select coalesce(c1.a, c2.a) a, c1.b, c2.c
from cte1 c1
full join cte2 c2 on c2.a = c1.a

Note that the CTEs are not actually needed here, you can use subqueries instead:

select coalesce(c1.a, c2.a) a, c1.b, c2.c
from (...) c1
full join (...) c2 on c2.a = c1.a
GMB
  • 216,147
  • 25
  • 84
  • 135
0

Use full outer join

select coalesce(table1.ColumnA,table2.ColumnA) as ColumnA,
       ColumnB,ColumnC  
from table1 full outer join table2 on table1.ColumnA=table2.ColumnA
Fahmi
  • 37,315
  • 5
  • 22
  • 31
0

You seem to want a full outer join here:

SELECT
    COALESCE(t1.A, t2.A) AS A,
    t1.B,
    t2.C
FROM Table1 t1
FULL OUTER JOIN t2
    ON t1.A = t2.A;

screen capture from demo link below

Demo

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360