简体   繁体   English

Oracle - 具有连接条件的外部连接

[英]Oracle - Outer Join with join condition

I have a scenario where I have two tables我有一个场景,我有两张桌子

ORDER命令

ORDER_NO
LOCATION
ITEM
QTY_RECEIVED

SHIPMENT运输

ORDER_NO
LOCATION
ITEM
QTY_RECEIVED

There are cases where ORDER table has a record but SHIPMENT table doesn't有些情况下 ORDER 表有记录但 SHIPMENT 表没有

I want all the rows from ORDER table where the qty is not equal to the qty in SHIPMENT table, and that will include the rows which are there in ORDER but not in shipment.我想要 ORDER 表中的所有行,其中数量不等于 SHIPMENT 表中的数量,这将包括 ORDER 中但不发货的行。

I tried doing by this:我试着这样做:

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);

But it doesn't give the correct result.但它没有给出正确的结果。

how should I do this?我该怎么做?

You need LEFT JOIN in order to return the the results even for the non-existing values of SHIPMENT table :即使对于 SHIPMENT 表的不存在值,您也需要 LEFT JOIN 才能返回结果:

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)) 

It seems possible to me that an order could have multiple shipments for the same item.在我看来,同一商品的订单可能有多次发货。 If this is the case, you need a different approach:如果是这种情况,您需要一种不同的方法:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM