-3

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.

4

3 回答 3

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

结果

| 项目 | 可用 |
----------------------
| 134 | 83 |

查看演示

于 2013-04-12T21:34:54.873 回答
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
于 2013-04-12T21:38:29.853 回答
0

另一种方法:

SELECT SUM(QTY) - 
       SUM(CASE WHEN [TYPE] IN ('UNUSED', 'FAULTY', 'DAMAGED') THEN QTY END) AS TotalSum
FROM TABLE1

演示:

于 2013-04-12T21:39:02.810 回答