计算一个 table SQL 服务器中的项目数量(SUM Outstanding of items)
Calculate item's quantity in one table SQL Server (SUM Outstanding of items)
我会在 SQL 服务器中询问有关总和的问题。
我有一个 table 可以存储这样的订单:
Code | items | Kinds | Qty |
-------------+-------------+---------------+--------+
PUR/2004/001 | b001 | PURCHASE | 5 |
PUR/2004/001 | b002 | PURCHASE | 10 |
PUR/2004/002 | b001 | PURCHASE | 3 |
REC/2004/001 | b001 | RECEIVE | 4 |
我需要的是一个查询来计算 table.
上每个项目的剩余余额
我想要的结果是这样的:
items | Outstanding Order |
-------------+---------------------+
b001 | 4 |
b002 | 10 |
我们可以在这里使用条件聚合:
SELECT
items,
SUM(CASE WHEN Kinds = 'PURCHASE' THEN Qty ELSE 0 END) -
SUM(CASE WHEN Kinds = 'RECEIVE' THEN Qty ELSE 0 END) AS [Outstanding Order]
FROM yourTable
GROUP BY
items;
有点不同的条件聚合方式:
SELECT
items,
SUM(CASE WHEN Kinds = 'PURCHASE' THEN Qty
WHEN Kinds = 'RECEIVE' THEN -Qty
END) AS [Outstanding Order]
FROM Table1
GROUP BY
items;
结果:
items Outstanding Order
b001 4
b002 10
我会在 SQL 服务器中询问有关总和的问题。
我有一个 table 可以存储这样的订单:
Code | items | Kinds | Qty |
-------------+-------------+---------------+--------+
PUR/2004/001 | b001 | PURCHASE | 5 |
PUR/2004/001 | b002 | PURCHASE | 10 |
PUR/2004/002 | b001 | PURCHASE | 3 |
REC/2004/001 | b001 | RECEIVE | 4 |
我需要的是一个查询来计算 table.
上每个项目的剩余余额我想要的结果是这样的:
items | Outstanding Order |
-------------+---------------------+
b001 | 4 |
b002 | 10 |
我们可以在这里使用条件聚合:
SELECT
items,
SUM(CASE WHEN Kinds = 'PURCHASE' THEN Qty ELSE 0 END) -
SUM(CASE WHEN Kinds = 'RECEIVE' THEN Qty ELSE 0 END) AS [Outstanding Order]
FROM yourTable
GROUP BY
items;
有点不同的条件聚合方式:
SELECT
items,
SUM(CASE WHEN Kinds = 'PURCHASE' THEN Qty
WHEN Kinds = 'RECEIVE' THEN -Qty
END) AS [Outstanding Order]
FROM Table1
GROUP BY
items;
结果:
items Outstanding Order
b001 4
b002 10