我有两张桌子:
采购订单:
PO # Part # PO Qty
S40000010 103-137 10
PO收据
PO # Part # Received Qty
S40000010 103-137 5
S40000010 103-137 3
如何编写sql语句以提取以下内容:
PO # Part # Balance Qty
S40000010 103-137 2
答案 0 :(得分:0)
你可以做到
SELECT po, part, SUM(qty) balance
FROM
(
SELECT po, part, qty
FROM PurchaseOrders
UNION ALL
SELECT po, part, -1 * qty
FROM POReceipts
) q
GROUP BY po, part;
或
SELECT p.po, p.part, p.qty - COALESCE(r.qty, 0) balance
FROM PurchaseOrders p LEFT JOIN
(
SELECT po, part, SUM(qty) qty
FROM POReceipts
GROUP BY po, part
) r
ON p.po = r.po AND p.part = r.part;
输出:
| PO | PART | BALANCE | |-----------|---------|---------| | S40000010 | 103-137 | 2 |
这是 SQLFiddle 演示
进一步阅读: