这是我的桌子形状:
---------------------------------------
ProductID | Reference | Qty |
---------------------------------------
1 | Plus | 8 |
---------------------------------------
1 | Minus | 2 |
---------------------------------------
2 | Plus | 18 |
---------------------------------------
2 | Minus | 6 |
---------------------------------------
2 | Minus | 3 |
---------------------------------------
结果将是这样。
----------------------------
ProductID | Rem. Qty |
----------------------------
1 | 6 |
----------------------------
2 | 9 |
----------------------------
答案 0 :(得分:4)
我们可以在此处尝试使用聚合:
SELECT
ProductID,
SUM(CASE WHEN Reference = 'Plus' THEN Qty ELSE -1.0 * Qty END) AS Total
FROM yourTable
GROUP BY
ProductID;