0

为了避免除以 0,我使用 CAST AS FLOAT 和 NULLIF。但由于某种原因,它给我的值是 0。我所做的只是划分 我做错了什么DeclinedSubmissions

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

在此处输入图像描述

4

2 回答 2

2

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

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

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;

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

我认为在“除以 0”的情况下返回 NULL 可能比返回 0 更好,因为 0 是真正的结果。

于 2016-09-02T00:48:25.483 回答
0

忘了说YEAR

WHERE YEAR(EffectiveDate) =2016 
于 2016-09-01T23:58:10.543 回答