1

如果我有 3 个如下表:

Table A:
Item Start_QTY
A    100
B    100

表 B:

Item Purchase_QTY
A    10
C    20

表 C:

Item End_QTY
A    90
B    10
C    10 

如何加入 2 个表以获得以下结果:

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

如果我执行以下操作:

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

我得到以下信息:

A 100 10 90
B 100 NULL 10
C NULL 20 NULL
C NULL NULL 10
4

2 回答 2

4

使用FULL OUTER JOIN从两个表中获取所有数据

尝试这个:

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;

::编辑::

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;
于 2014-12-29T13:15:52.130 回答
1

如果您希望它同时在 SQL Server 和 MySQL 中工作,那么您不能使用full outer join. 以下可能会做你想做的事:

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;

仅在 SQL Server 中,您应该使用full outer join.

于 2014-12-29T13:22:08.140 回答