我有一个看起来像这样的表:
+----+------+--------+----------+
| ID | Code | OpType | Quantity |
+----+------+--------+----------+
| 0 | A | IN | 7 |
| 1 | B | IN | 8 |
| 2 | A | OUT | 2 |
| 3 | B | IN | 7 |
| 4 | B | OUT | 12 |
+----+------+--------+----------+
我想要 SUM(Quantity) 取决于 OpType。当 OpType 为 OUT 时,Quantity 字段应乘以 -1。
查询的结果应该是:
Code IN OUT Final
A 7 2 5
B 15 12 3
我试过这个,但它不起作用:
SELECT(SELECT SUM(Quantity) FROM Table WHERE OpType = 'IN') AS[IN], (SELECT SUM(Quantity) FROM Table WHERE OpType = 'OUT') AS[OUT], (SELECT SUM(Quantity) FROM Table WHERE OpType = 'IN') - (SELECT SUM(Quantity) FROM Table WHERE OpType = 'OUT') AS[Final]
FROM Table
GROUP BY Code