1

我的目标是检索已接受采购订单上某件商品的记录采购价格。

Purchase_Orders表包含订单的元数据,例如订单号及其状态(例如,1 表示接受,0 表示拒绝)。

Purchase_Ord_Contents表包含内容记录,这些记录通过外键链接到共享索引上的父采购订单order_number)

例如:我的数据库中有两个订单,一个已被接受,另一个已被拒绝。数据表示如下:

 =========================================
           PURCHASE_ORDERS TABLE
 =========================================
 id   |   order_number   |   order_status
 -----------------------------------------
  1          PO_100               0
  2          PO_101               1
  3          PO_102               1

===================================================
           PURCHASE_ORD_CONTENTS TABLE
===================================================
id    | order_number | purchase_price |    sku
---------------------------------------------------
   1       PO_100           1.50          APPLE
   2       PO_100           1.50          ORANGE
   3       PO_101           2.00          APPLE
   4       PO_101           2.00          ORANGE
   5       PO_102           1.75          BANANA

查询应返回第 3、4 和 5 行,因为PO_101被接受,而PO_100被拒绝,第 5 行不仅是给定 SKU 的唯一记录,而且还在接受的订单上。我尝试了几种不同的方法,但我似乎总是要么遗漏未接受的采购订单上的零件,要么检索错误order_number的最低purchase_price.

这是我到目前为止所拥有的(无法正常工作)

SELECT a.*
FROM   purchase_ord_contents AS a
       JOIN (SELECT sku,
                    MIN(purchase_price) AS min_price
             FROM   purchase_ord_contents
             GROUP  BY sku) AS b
         ON ( a.sku = b.sku
              AND a.purchase_price = b.min_price )
WHERE a.order_number
IN (
   SELECT order_number
   FROM purchase_orders
   WHERE order_status != 0
)

此查询成功地从表中返回记录,但是它忽略了采购订单上purchase_ord_contents的最低记录,其值为 0。purchase_priceorder_status

任何指导将不胜感激,我不太精通“高级” SQL 查询,正如您现在可能已经确定的那样。感谢您抽出宝贵时间,请随时询问我是否应该提供任何进一步的信息。

4

2 回答 2

1

这可能是您正在寻找的:

SELECT sku, purchase_price, order_number
FROM (
    SELECT MIN(purchase_price) AS purchase_price, sku
    FROM purchase_ord_contents
    JOIN purchase_orders USING (order_number)
    WHERE purchase_orders.order_status = 1
    GROUP BY sku
) AS min_sku_price -- this is the lowest sale price for each SKU
JOIN purchase_ord_contents USING (sku, purchase_price) -- gets all orders having sold a SKU at its lowest price
JOIN purchase_orders USING (order_number)
WHERE purchase_orders.order_status = 1

请注意,如果该 SKU 的最低价格在多个订单中提供,这将返回一个给定 SKU 的多行。

于 2013-06-25T21:36:13.860 回答
0

如果我理解正确,我认为你想要这个:

SELECT po.order_number, poc.sku, min(poc.purchase_price)
FROM purchase_orders AS po
 JOIN purchase_ord_contents AS poc ON poc.order_number = po.order_number
 WHERE po.order_status != 0
 GROUP by po.order_number, poc.sku
 order by po.order_number, poc.sku
于 2013-06-25T21:20:40.817 回答