SQL语句 - 第1表的数量减去第2表的数量总和

时间:2014-09-26 00:39:28

标签: sql subquery

我有两张桌子:

采购订单:

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

1 个答案:

答案 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 演示

进一步阅读: