对于每个仓库,我需要获得每种产品的估计数量。此数量是根据上一个库存中记录的数量计算的,减去自上次库存以来的出货量,加上自上次库存以来的重新供应。
以下是我的实体:
-warehouse
location
-inventory
date
-product
name
-inventory_product
quantity
warehouse_id
product_id
inventory_id
-resupply
date
-resupplying
resupply_id
product_id
warehouse_id
quantity
-shipment
date
-shipping
shipment_id
product_id
warehouse_id
quantity
我正在考虑......的一些事情。
select distinctrow product.name, inventory_product.quantity - sum(shipping.quantity) as quantity
from inventory
inner join inventory_product on inventory.id = inventory_product.inventory_id
inner join product on inventory.product_id = product.id
inner join shipping on (inventory_product.warehouse_id = shipping.warehouse_id and inventory_product.product_id = shipping.product_id)
inner join shipment on shipping.shipment_id = shipment.id
where inventory.date <= shipment.date
group by shipping.product_id;
但我看不出如何添加补给部分......
答案 0 :(得分:1)
考虑拆分单元级别和聚合级别部分,然后将它们连接在一起以进行最终算术表达。将每个保存为要在其他查询的FROM/JOIN
子句中引用的存储查询。
上次库存日期查询 (按product_id汇总)
SELECT i.product_id, Max(n.date) AS MaxInvDate
FROM inventory AS n
INNER JOIN inventory_product AS i ON n.id = i.inventory_id
GROUP BY i.product_id;
货件总和查询 (在上面的MaxInvDate上和之后总和数量)
SELECT i.product_id, i.quantity AS inv_qty, idt.date AS inv_date,
SUM(s.quantity) AS shipment_qty
FROM ((inventory_product i INNER JOIN inventory idt ON idt.id = i.inventory_id)
INNER JOIN (shipping s INNER JOIN shipment sdt ON sdt.id = s.shipment_id)
ON s.product_id = i.product_id)
INNER JOIN LastInvDateQ l
ON l.product_id = i.product_id AND idt.date = l.MaxInvDate
WHERE sdt.date >= l.MaxInvDate
GROUP BY i.product_id, i.quantity, idt.date
补给资源总和查询 (在上面的MaxInvDate之后加上数量)
SELECT i.product_id, i.quantity AS inv_qty, idt.date AS inv_date,
SUM(r.quantity) AS resupply_qty
FROM ((inventory_product i INNER JOIN inventory idt ON idt.id = i.inventory_id)
INNER JOIN (resupplying r INNER JOIN resupply rdt ON rdt.id = r.resupply_id)
ON r.product_id = i.product_id)
INNER JOIN LastInvDateQ l
ON l.product_id = i.product_id AND idt.date = l.MaxInvDate
WHERE rdt.date >= l.MaxInvDate
GROUP BY i.product_id, i.quantity, idt.date
最终查询
SELECT s.product_id, s.inv_date, s.inv_qty, s.shipment_qty, r.resupply_qty,
(s.inv_qty - s.shipment_qty + r.resupply_qty) as estimated_qty
FROM ShipQtyAggQ s
INNER JOIN ResupplyQtyAggQ r ON (s.inv_date = r.inv_date)
AND (s.inv_qty = r.inv_qty)
AND (s.product_id = r.product_id);
当然,您可以将每个SELECT
语句作为派生表嵌套在最终查询中,但可能会变得难以阅读和/或维护。