oracle SQL - 从总数中减去某些记录的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15981149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL - Subtract the sum of certain records from the total
提问by user1296490
Given the following table
鉴于下表
ITEMID | TYPE | QTY |
-----------------------
...
134 |TOTALINDEPOT | 169 |
134 |UNUSED | 70 |
134 |FAULTY | 15 |
134 |DAMAGED | 1 |
134 |DELAYED | 100 |
...
What is an efficient way to retrieve the quantity of available items with id 134 (excluding these of delayed type)? Result is 83 => (169-(70+15+1)).
I implemented it with (SELECT qty FROM tableA WHERE type='TOTALINDEPOT' AND itemid='134') - (SELECT SUM(qty) ... WHERE TYPE IN ('UNUSED', 'FAULTY', 'DAMAGED')) AND itemid='134'
, but looking for something more elegant.
检索 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'
,但寻找更优雅的东西。
回答by Kermit
Like this?
像这样?
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
Result
结果
| ITEMID | AVAILABLE | ---------------------- | 134 | 83 |
回答by a1ex07
Will it work for you?
对你有用吗?
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