SQL - 从总计中减去某些记录的总和

时间:2013-04-12 21:28:54

标签: sql oracle

给出下表

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'实现了它,但寻找更优雅的东西。

3 个答案:

答案 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 |

See the demo

答案 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

DEMO: