MySQL查询库存制造

p3rjfoxz  于 2023-10-15  发布在  Mysql
关注(0)|答案(1)|浏览(91)

我有一个关于制造业库存的项目,在那里我有

产品列表

id (primary id),
product_name,
initial_qty,
type

purchase_order_details表

id
, product_id (foreign_key)
 , quantity

work_order_details表

id
, product_id (foreign_key)
, quantity

装配表

id (primary id)
, product_id (foreign_key)

boms Table

id,
 assembly_id (foreign_key),
 product_id ( foreign_key),
 quantity

在此表中,我需要根据公式为products.initial_qty + purchase_order_details.quantity - work_order_details quantity的记录获取产品表数量的当前库存。
如果工作订单product_id的方案是组件(产品类型),则此公式是正确的。如果场景是工作订单是装配(产品类型),即与装配表和BOM表相关,则我会迷路。这是我的示例查询。希望有人能帮助我堆叠已经近3天。

SELECT 
    p.id,
    p.product_name,
    COALESCE(SUM(pod.quantity), 0) AS purchase_quantity,
    COALESCE(SUM(pod.quantity)  - SUM(b.quantity_boms), 0) AS final_quantity
FROM 
    products p
LEFT JOIN 
    purchase_order_details pod ON p.id = pod.product_id

LEFT JOIN 
    (SELECT a.product_id, SUM(b.quantity) AS quantity_boms
     FROM assemblies a
     LEFT JOIN boms b ON a.id = b.assembly_id 
     WHERE a.product_id IN (SELECT product_id FROM work_order_details)
     GROUP BY a.id) b ON p.id = b.product_id
GROUP BY 
    p.id, p.product_name;

SELECT 
    p.id,
    p.product_name,
    COALESCE(SUM(pod.quantity), 0) AS purchase_quantity,
    COALESCE(SUM(pod.quantity)  - SUM(b.quantity_boms), 0) AS final_quantity
FROM 
    products p
LEFT JOIN 
    purchase_order_details pod ON p.id = pod.product_id

LEFT JOIN 
    (SELECT b.product_id, b.quantity AS quantity_boms
     FROM assemblies a
     LEFT JOIN boms b ON a.id = b.assembly_id 
     WHERE a.product_id IN (SELECT product_id FROM work_order_details)
     GROUP BY b.product_id, b.quantity ) b ON p.id = b.product_id
GROUP BY 
    p.id, p.product_name;

n9vozmp4

n9vozmp41#

我改变了关系。我添加了assembly_work_order表,它记录了与装配相关的work_order_order。我将所有product_id和include的总和添加到final_quantity中。这是我最终的结果

SELECT 
    p.id AS product_id,
    p.product_name,
    (p.quantity + COALESCE(po.total_quantity, 0) - COALESCE(wd.total_quantity, 0) - COALESCE(awo.total_quantity, 0)) AS current_inventory
FROM 
    Products p
LEFT JOIN
    (SELECT product_id, SUM(quantity) AS total_quantity FROM purchase_order_details GROUP BY product_id) po
ON 
    p.id = po.product_id
LEFT JOIN
    (SELECT product_id, SUM(quantity) AS total_quantity FROM assembly_work_orders GROUP BY product_id) awo
ON 
    p.id = awo.product_id
LEFT JOIN
    (SELECT product_id, SUM(quantity) AS total_quantity FROM work_order_details GROUP BY product_id) wd
ON 
    p.id = wd.product_id;

相关问题