我正在处理一个查询,该查询会进行一些数学运算,特别是总计和百分比。由于此数据是基于所选日期范围的可选数据,因此有时无法执行此数学运算。
在这种情况下,我得到了除以零的错误。
SELECT (
SELECT COUNT(s.ScoreID) AS TotalSamples,
COUNT(CASE WHEN qd.QDResultDesc = 'Pass' THEN 1 END) AS Pass,
COUNT(CASE WHEN qd.QDResultDesc = 'Pass' THEN 1 END) * 100 / COUNT(s.ScoreID) AS Quality,
COUNT(CASE WHEN qd.QDResultDesc = 'Fail' THEN 1 END) AS Fail,
COUNT(CASE WHEN qd.QDResultDesc = 'Fail' THEN 1 END) * 100 / COUNT(s.ScoreID) AS Error
FROM SubmissionScore AS s
JOIN gSubmission AS sub
ON sub.SubmissionID = s.RecordID
JOIN gQDResult AS qd
ON s.QDResultID = qd.QDResultID
JOIN resources.emp.Employees as e
ON sub.TeammateQID = e.QID
WHERE e.CampusID = 66 -- Chennai
FOR XML PATH ('overall'), ELEMENTS, TYPE, ROOT ('chennai')
)
FOR XML PATH ('data'), ELEMENTS, TYPE, ROOT ('root');
我尝试添加ISNULL
来解决缺失的部分,但这似乎无法解决。
在上面的查询中,如果没有数据,我希望输出仅为0
。
是否有一种简单的方法来调整此代码以解决此问题?
答案 0 :(得分:8)
您要查找的是NULLIF()
,而不是ISNULL()
:
COUNT(CASE WHEN qd.QDResultDesc = 'Pass' THEN 1 END) * 100 / NULLIF(COUNT(s.ScoreID), 0) AS Quality,
您可能还需要* 100.0
,因为SQL Server会执行整数运算。