1

If I have 3 tables like the following:

Table A:
Item Start_QTY
A    100
B    100

Table B:

Item Purchase_QTY
A    10
C    20

Table C:

Item End_QTY
A    90
B    10
C    10 

How do I join the 2 tables to get the following result:

Item Start_QTY  Purchase_QTY  End_QTY
A    100  10 90
B    100  NULL 10
C    NULL 20 10

If I do the following:

Select COALESCE(a.item, b.item, c.item) as item, a.start_QTY, b.purchase_QTY, c.End_QTY from 
A as a 
full outer join 
B as b
on a.item = b.item
full outer join
C as c
on a.item = c.item

I get the following:

A 100 10 90
B 100 NULL 10
C NULL 20 NULL
C NULL NULL 10
Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
calvin12
  • 211
  • 1
  • 5
  • 16

2 Answers2

4

Use FULL OUTER JOIN to fetch all the data from both tables

Try this:

SELECT COALESCE(A.Item, B.Item) AS Item, A.QTY, B.Price
FROM TableA A 
FULL OUTER JOIN TableB B ON A.Item = B.Item;

::EDIT::

SELECT COALESCE(C.Item, A.Item, B.Item) AS Item, A.Start_QTY, B.Purchase_QTY, C.End_QTY
FROM TableC C  
FULL OUTER JOIN TableA A ON C.Item = A.Item
FULL OUTER JOIN TableB B ON C.Item = B.Item;
Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
1

If you want it to work in both SQL Server and MySQL, then you cannot use full outer join. The following may do what you want:

select item, max(qty) as qty, max(price) as price
from (select item, qty, null as price
      from tablea 
      union all
      select item, null, price
      from tableb
     ) ab
group by item;

In SQL Server alone, you should use full outer join.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786