【问题标题】:mySQL Sum Production_Needed Group BY Part_IDmySQL Sum Production_Needed Group BY Part_ID
【发布时间】:2021-07-06 15:36:55
【问题描述】:

想要在需要生产的情况下生成未结订单的结果。问题是每个部分可能有多个未结订单。使用 GROUP BY,我的代码只给了我一个订单,但确实给了我总 Production_Needed(对于有足够库存的订单,这也是一个负值)。

我的 SUM(...) 作为 Production_Needed 是否需要在 WHERE 中? 谢谢,

SELECT part.part_ID AS Part_Part_ID, 
   part.Inventory, part.part_number, 
   ord.part_id AS Order_Part_ID, 
   ord.order_type, ord.quantity_ordered, ord.quantity_shipped, 
   SUM(ord.quantity_ordered - ord.quantity_shipped - part.Inventory) AS Production_Needed 
FROM production_orders ord 
JOIN production_part part ON ord.part_ID = part.part_ID 
WHERE ord.is_Active = True AND ord.order_type = 0
GROUP BY Order_Part_ID 
ORDER BY part.part_number ASC

数据生产_Part部分

Part_ID Part_Inventory Part_Number
1 12500 97-528
2 0 FC2569
3 1000 39367

数据生产_订单订单

Order_Part_ID Order_Type Quantity_Ordered Quantity_Shipped
1 0 8000 0
2 0 1000 500
2 0 1000 0
3 1 10 0

期望的结果 - 仅需要生产的零件

Part_ID Quantity_Ordered Quantity_Shipped
2 1000 500
2 1000 0

【问题讨论】:

  • 请用一些示例数据(查询的来源和结果)编辑您的问题
  • 从逻辑上讲,我认为您希望在从库存中减去之前对订单数量进行汇总。这就是为什么...假设您有 3 个 10x0、20x0、30x10 的项目 A 订单,并且您有 5 个库存。这意味着您总共订购了 60 个,并且已发货 10 个。如果按照您概述结果的方式进行操作,则结果将是 (10-0-5)+(20-0-5)+(30-10-5) 请注意它如何从每个订单中的库存中减去 5。你只希望这种情况发生一次。

标签: mysql group-by sum


【解决方案1】:

未测试:需要一个采样数据集和结构进行测试:

这会创建一个内联视图并汇总库存订单数量,然后将其从库存中提取出来,以确定是否需要生产来完成未结订单。但是,如果我们需要按订单执行此操作,我将不得不使用一些额外的分析功能;或者将这些结果重新加入订单...

--显示缺少库存以完成未完成的未结订单的零件。

SELECT 
    P.Part_ID as Part_Part_ID
  , P.Inventory
  , P.Part_Number
  , O.Part_ID as Order_Part_ID
  , UnDel_Units-coalesce(P.Inventory,0) as Production_Needed  --use coalesce incase no part record exists for some reason.
FROM Production_Part P
RIGHT JOIN (    --use right join just incase part record doesn't exist for some reason
  SELECT part_ID, SUM(quantity_ordered-quantity_shipped) as UnDel_Units
  FROM PRODUCTION_ORDERS
  WHERE IS_ACTIVE=TRUE
    and ORDER_TYPE=0
  GROUP BY PART_ID) O  --derived table "O" for orders showing sum ottal by part of units undelivered
 on O.Part_ID=P.Part_ID
WHERE UnDel_Units > coalesce(P.Inventory,0)
--  If inventory is > undelivered units for the part, ignore as additional production isn't needed

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-09
    • 2017-10-20
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多