我希望我的sum函数返回'0',如果某个值不存在,任何人都可以识别以下SQL命令是否存在问题。我已经改变了合并的顺序,但这并没有什么不同
SqlCommand scGetPostings = new SqlCommand(@"
SELECT
D1.dr,
D1.cr,
D1.asset_no,
(open_bal + dr - cr) AS closing_balance
FROM (SELECT
COALESCE(SUM(dr_amount), 0) AS dr,
COALESCE(SUM(cr_amount), 0) AS cr,
asset_no
FROM posting, sysasset
WHERE posting.asset_no = @AssetNumber
AND period >= asset_open_per
GROUP BY asset_no) AS D1, asset
WHERE D1.asset_no = asset.asset_no", DataAccess.AssetConnection);
答案 0 :(得分:0)
试试这个:
SELECT
asset.asset_no,
COALESCE(dr, 0) AS dr,
COALESCE(cr, 0) AS cr,
(open_bal + COALESCE(dr, 0) - COALESCE(cr, 0)) AS closing_balance
FROM
asset LEFT JOIN
(SELECT
SUM(dr_amount) AS dr,
SUM(cr_amount) AS cr,
asset_no
FROM posting, sysasset
WHERE posting.asset_no = @AssetNumber
AND period >= asset_open_per
GROUP BY asset_no) AS D1
ON D1.asset_no = asset.asset_no
答案 1 :(得分:0)
在您的陈述中使用if condition
:
SqlCommand scGetPostings = new SqlCommand(@"
SELECT
D1.dr,
D1.cr,
D1.asset_no,
(open_bal + dr - cr) AS closing_balance
FROM (SELECT
SUM(if(dr_amount is null , 0 , dr_amount )) AS dr,
SUM(if(cr_amount is null , 0 , cr_amount )) AS cr,
asset_no
FROM posting, sysasset
WHERE posting.asset_no = @AssetNumber
AND period >= asset_open_per
GROUP BY asset_no) AS D1, asset
WHERE D1.asset_no = asset.asset_no", DataAccess.AssetConnection);