我有两个表,都有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
答案 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;
例如,如果您想要查看这两个数字及其差异,则可以轻松地重复使用这些值。