你想做什么的大纲很好,但不是你实现的。
- 我想将所有
product_quantity 与table1 相加,其中product_id = '$this' 和所有order_quantity 与table2 相加,其中product_hashid = '$this' 并生成(a - b) 以显示最终结果。
一步一步构建它。
SELECT SUM(product_quantity) FROM Table1 WHERE Product_ID = '$this';
SELECT SUM(order_quantity) FROM Table2 WHERE Product_HashID = '$this';
SELECT (SELECT SUM(product_quantity) FROM Table1 WHERE Product_ID = '$this') -
(SELECT SUM(order_quantity) FROM Table2 WHERE Product_HashID = '$this')
FROM Dual;
您可能会观察到代码对齐强调了产品 ID 列的不一致列命名。
在更一般的情况下:
SELECT Product_ID, SUM(product_quantity) AS Product_Quantity
FROM Table1
GROUP BY Product_ID;
SELECT Product_HashID AS Product_ID, SUM(order_quantity) AS Order_Quantity
FROM Table2
GROUP BY Product_HashID;
SELECT p.Product_ID, p.Product_Quantity - o.Order_Quantity AS SurplusOnHand
FROM (SELECT Product_ID, SUM(product_quantity) AS Product_Quantity
FROM Table1
GROUP BY Product_ID) AS P
JOIN (SELECT Product_HashID AS Product_ID, SUM(order_quantity) AS Order_Quantity
FROM Table2
GROUP BY Product_HashID) AS O
ON O.Product_ID = P.Product_ID;
有时您需要使用 LEFT OUTER JOIN;大多数情况下,你没有。假设你没有写你的 SQL,直到你确定你这样做。
鉴于数据基数(行数),您可能需要在此处执行 LOJ。表1中未列在表2中的产品的订货量需要制造为零。
SELECT (SELECT SUM(product_quantity) FROM Table1 WHERE Product_ID = '$this') -
NVL(SELECT SUM(order_quantity) FROM Table2 WHERE Product_HashID = '$this'), 0)
FROM Dual;
SELECT p.Product_ID, p.Product_Quantity - NVL(o.Order_Quantity, 0) AS SurplusOnHand
FROM (SELECT Product_ID, SUM(product_quantity) AS Product_Quantity
FROM Table1
GROUP BY Product_ID) AS P
LEFT OUTER JOIN
(SELECT Product_HashID AS Product_ID, SUM(order_quantity) AS Order_Quantity
FROM Table2
GROUP BY Product_HashID) AS O
ON O.Product_ID = P.Product_ID;