Oracle - 具有连接条件的外部连接
Oracle - Outer Join with join condition
我有一个场景,我有两个 table
订单
ORDER_NO
LOCATION
ITEM
QTY_RECEIVED
发货
ORDER_NO
LOCATION
ITEM
QTY_RECEIVED
有些情况下 ORDER table 有记录但 SHIPMENT table 没有
我想要 ORDER table 中的所有行,其中数量不等于 SHIPMENT table 中的数量,并且将包括 ORDER 中但不在装运中的行。
我试过这样做:
SELECT
order_no, item, location, SUM(NVL(QTY_RECEIVED, 0))
FROM
ORDERS ol
GROUP BY
ORDER_NO, ITEM, LOCATION
HAVING
SUM (NVL(ol.QTY_RECEIVED,0)) <>
(SELECT SUM(NVL(sk.QTY_RECEIVED, 0))
FROM shipment s
WHERE s.order_no = ol.order_no
AND s.item (+)= ol.item
AND s.location (+) = ol.location
GROUP BY s.order_no, s.item, s.location);
但它没有给出正确的结果。
我应该怎么做?
您需要 LEFT JOIN 才能 return 结果,即使是 SHIPMENT table 的不存在值也是如此:
SELECT ol.order_no, ol.item, ol.location,
SUM(NVL(ol.QTY_RECEIVED, 0)) AS "Total Quantity Of Orders",
SUM (NVL(s.QTY_RECEIVED,0)) AS "Total Quantity Of Shpm."
FROM orders ol
LEFT JOIN shipment s
ON s.order_no = ol.order_no
AND s.item = ol.item
AND s.location = ol.location
GROUP BY ol.order_no, ol.item, ol.location
HAVING SUM (NVL(ol.QTY_RECEIVED,0)) <> SUM (NVL(s.QTY_RECEIVED,0))
在我看来,同一个商品可能有多个订单。如果是这种情况,您需要一种不同的方法:
select order_no, location, item, sum(o_qty), sum(s_qty)
from ((select order_no, location, item, qty_received as o_qty, 0 as s_qty
from orders
) union all
(select order_no, location, item, 0 as o_qty, qty_received as s_qty
from shipment
)
) os
group by order_no, location, item
having sum(o_qty) <> sum(s_qty);
我有一个场景,我有两个 table
订单
ORDER_NO
LOCATION
ITEM
QTY_RECEIVED
发货
ORDER_NO
LOCATION
ITEM
QTY_RECEIVED
有些情况下 ORDER table 有记录但 SHIPMENT table 没有
我想要 ORDER table 中的所有行,其中数量不等于 SHIPMENT table 中的数量,并且将包括 ORDER 中但不在装运中的行。
我试过这样做:
SELECT
order_no, item, location, SUM(NVL(QTY_RECEIVED, 0))
FROM
ORDERS ol
GROUP BY
ORDER_NO, ITEM, LOCATION
HAVING
SUM (NVL(ol.QTY_RECEIVED,0)) <>
(SELECT SUM(NVL(sk.QTY_RECEIVED, 0))
FROM shipment s
WHERE s.order_no = ol.order_no
AND s.item (+)= ol.item
AND s.location (+) = ol.location
GROUP BY s.order_no, s.item, s.location);
但它没有给出正确的结果。
我应该怎么做?
您需要 LEFT JOIN 才能 return 结果,即使是 SHIPMENT table 的不存在值也是如此:
SELECT ol.order_no, ol.item, ol.location,
SUM(NVL(ol.QTY_RECEIVED, 0)) AS "Total Quantity Of Orders",
SUM (NVL(s.QTY_RECEIVED,0)) AS "Total Quantity Of Shpm."
FROM orders ol
LEFT JOIN shipment s
ON s.order_no = ol.order_no
AND s.item = ol.item
AND s.location = ol.location
GROUP BY ol.order_no, ol.item, ol.location
HAVING SUM (NVL(ol.QTY_RECEIVED,0)) <> SUM (NVL(s.QTY_RECEIVED,0))
在我看来,同一个商品可能有多个订单。如果是这种情况,您需要一种不同的方法:
select order_no, location, item, sum(o_qty), sum(s_qty)
from ((select order_no, location, item, qty_received as o_qty, 0 as s_qty
from orders
) union all
(select order_no, location, item, 0 as o_qty, qty_received as s_qty
from shipment
)
) os
group by order_no, location, item
having sum(o_qty) <> sum(s_qty);