除法给出值 0

Division gives values 0

为了避免除以 0,我使用 CAST AS FLOAT 和 NULLIF。 但出于某种原因,它给我的值为 0。 我所做的就是将 Declined 除以 Submissions 我做错了什么?

SELECT          [Status Reason],
                b.MonthNum,
                b.YearNum,
                ISNULL(SUM(CASE WHEN  Status = 'Declined' THEN 1 ELSE 0 END ),0) as  Declined,
                (
                    SELECT  COUNT(ControlNo) 
                    FROM    ClearanceReportMetrics 
                    WHERE   YEAR(EffectiveDate) =YEAR(GETDATE())  AND CompanyLine = 'Ironshore Insurance Company' 
                    AND LineOfBusiness NOT IN ('SSP Commercial General Liability','SSP Property') AND Underwriter <> 'Batcheller, Jerry'
                ) AS Submissions,

        /*And this is what gives 0's  */

                COALESCE(CAST(SUM(CASE WHEN  Status = 'Declined' THEN 1 ELSE 0 END ) AS FLOAT) /
                (           /* Here I am using NULLIF to avoid division by 0 */
                    SELECT  NULLIF(COUNT(ControlNo),0) 
                    FROM    ClearanceReportMetrics 
                    WHERE   EffectiveDate =YEAR(GETDATE())  AND CompanyLine = 'Ironshore Insurance Company' 
                            AND LineOfBusiness NOT IN ('SSP Commercial General Liability','SSP Property') AND Underwriter <> 'Batcheller, Jerry'
                ),0) AS DeclinedRatio

FROM        tblCalendar b
LEFT JOIN   ClearanceReportMetrics a ON b.MonthNum = MONTH(a.EffectiveDate) and b.YearNum = YEAR(a.EffectiveDate) 
                --AND   EffectiveDate >=DateAdd(yy, -1, DATEADD(d, 1, EOMONTH(GETDATE()))) AND EffectiveDate <= EOMONTH(GETDATE())  AND CompanyLine = 'Ironshore Insurance Company' AND Status = 'Declined'
                --AND LineOfBusiness NOT IN ('SSP Commercial General Liability','SSP Property') 
WHERE       b.YearNum = YEAR(GETDATE())
GROUP BY    b.YearNum,b.MonthNum,[Status Reason]
ORDER BY    b.YearNum, b.MonthNum   ,Declined DESC

忘记在

中说 YEAR
WHERE YEAR(EffectiveDate) =2016 

这是解决它的一种方法,并且使查询更易于阅读(删除了计算拒绝和提交的代码的令人讨厌的重复)。

使用虚拟内部数据的示例。将比率计算移至外部查询。

SELECT
   x.*
  ,CASE
       WHEN Submissions > 0
       THEN CAST(Declined AS FLOAT) / Submissions
       ELSE NULL
   END DeclinedRatio
FROM
(
    -- Dummy data, replace with existing query (except ratio calculation).
    SELECT
           'Does Not Meet Underwriting Guidelines' [Status Reason]
          ,1 MonthNum
          ,2016 YearNum
          ,5 Declined
          ,10 Submissions
) x;

假设,拒绝次数永远不会超过提交次数。

我认为在 "divide by 0" 情况下 return NULL 可能比 0 更好,因为 0 是真实结果。