在两个子查询中添加Case,在subtract上返回null

时间:2015-05-27 21:42:29

标签: sql .net database

我有两个表,都有qty列,我想从issued_donated_items中减去donated_items。它工作正常,直到issued_donated_items中没有记录,然后我的查询返回null

SELECT 
(
(SELECT Sum(quantity) AS tQty  FROM donated_items WHERE item_id=4)

-

(SELECT Sum(quantity_issued) AS issueQty  FROM issued_donated_items WHERE item_id=4)

)AS total

2 个答案:

答案 0 :(得分:1)

像这样使用 isnull()

SELECT 
(
(SELECT Sum(isnull(quantity,0)) AS tQty  FROM donated_items WHERE item_id=4)

-

(SELECT Sum(isnull(quantity_issued,0)) AS issueQty  FROM issued_donated_items WHERE item_id=4)

)AS total

对于ANSI标准SQL,使用 coalesce()而不是 isnull()

答案 1 :(得分:1)

我建议将子查询移到from子句并使用coalesce()

SELECT (COALESCE(di.QTY, 0) - COALESCE(idi.issueQTY, 0)
       ) AS total
FROM (SELECT Sum(quantity) AS tQty FROM donated_items WHERE item_id = 4) di CROSS JOIN
     (SELECT Sum(quantity_issued) AS issueQty FROM issued_donated_items WHERE item_id = 4) idi;

例如,如果您想要查看这两个数字及其差异,则可以轻松地重复使用这些值。