给出下表
ITEMID | TYPE | QTY |
-----------------------
...
134 |TOTALINDEPOT | 169 |
134 |UNUSED | 70 |
134 |FAULTY | 15 |
134 |DAMAGED | 1 |
134 |DELAYED | 100 |
...
检索ID为134的可用商品数量的有效方法是什么(不包括延迟类型)?结果是83 => (169-(70 + 15 + 1))。
我用(SELECT qty FROM tableA WHERE type='TOTALINDEPOT' AND itemid='134') - (SELECT SUM(qty) ... WHERE TYPE IN ('UNUSED', 'FAULTY', 'DAMAGED')) AND itemid='134'
实现了它,但寻找更优雅的东西。
答案 0 :(得分:2)
喜欢这个吗?
SELECT a.ITEMID,
(SELECT SUM(QTY) FROM tbl WHERE TYPE = 'TOTAL' AND ITEMID = a.ITEMID) -
(SELECT SUM(QTY) FROM tbl WHERE TYPE <> 'TOTAL' AND ITEMID = a.ITEMID) AS available
FROM tbl a
GROUP BY a.ITEMID
<强>结果强>
| ITEMID | AVAILABLE | ---------------------- | 134 | 83 |
答案 1 :(得分:0)
它会对你有用吗?
SELECT a.total1 - a.total2
FROM
(
SELECT SUM(CASE WHEN type='total' THEN qty ELSE 0 END) as total1,
SUM(CASE WHEN type<>'total' THEN qty ELSE 0 END) as total2
FROM table WHERE itemid = 134
)a
答案 2 :(得分:0)
还有一种方法:
SELECT SUM(QTY) -
SUM(CASE WHEN [TYPE] IN ('UNUSED', 'FAULTY', 'DAMAGED') THEN QTY END) AS TotalSum
FROM TABLE1