我已经写了一个查询来提取所有未完成的延期交货,只显示可以履行的行(根据订单数量检查库存水平)。
我想将每个订单汇总成一行。
客户名称/订单ID /总和(未结数量)/总和(qtyToSend)/ sum(unitSell)
目前我的输出看起来像这样 - 如果有人可以提供任何指导或指出我正确的方向,我将不胜感激。
SELECT
c.cus_name,
ol.orderLines_orderId,
oh.orderHeader_status,
ol.orderLines_stockRef,
ol.orderLines_qtyOrdered,
ol.orderlines_qtyInvoiced,
ol.orderLines_qtyOrdered - ol.orderlines_qtyInvoiced as qtyOutstanding,
(CASE
WHEN ol.orderLines_qtyOrdered - ol.orderlines_qtyInvoiced > pr.products_instock THEN pr.products_instock
ELSE (ol.orderLines_qtyOrdered - ol.orderlines_qtyInvoiced)
END) AS qtyToSend,
pr.products_instock,
FORMAT(ol.orderLines_totalSell/ol.orderLines_qtyOrdered,2) as unitSell
FROM
cus c
JOIN
orderheader oh ON oh.orderHeader_customer = c.cus_id
JOIN
orderlines ol ON ol.orderLines_orderId = oh.orderHeader_id
JOIN
products pr ON ol.orderlines_stockref = pr.products_reference
WHERE
ol.orderLines_qtyOrdered <> ol.orderlines_qtyInvoiced
HAVING
qtytosend > 0
我试过这样做,但订单的价值不正确。根据我对第1行(Emiliano's Gifts Bros)的计算,延期交货的总价值应为34.42英镑
SELECT
c.cus_name,
ol.orderLines_orderId,
sum(ol.orderLines_qtyOrdered - ol.orderlines_qtyInvoiced )as qtyOutstanding,
sum((CASE
WHEN ol.orderLines_qtyOrdered - ol.orderlines_qtyInvoiced > pr.products_instock THEN pr.products_instock
ELSE (ol.orderLines_qtyOrdered - ol.orderlines_qtyInvoiced)
END))AS qtyToSend,
sum(FORMAT(ol.orderLines_totalSell/ol.orderLines_qtyOrdered,2)) as unitSell
FROM
cus c
JOIN
orderheader oh ON oh.orderHeader_customer = c.cus_id
JOIN
orderlines ol ON ol.orderLines_orderId = oh.orderHeader_id
JOIN
products pr ON ol.orderlines_stockref = pr.products_reference
WHERE
ol.orderLines_qtyOrdered <> ol.orderlines_qtyInvoiced
GROUP BY
ol.orderLines_orderId
HAVING
qtytosend > 0