除法给出值0

时间:2016-09-01 23:30:33

标签: sql tsql casting zero nullif

为了避免除以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

enter image description here

2 个答案:

答案 0 :(得分: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是真实结果。

答案 1 :(得分:0)

忘了在

中说YEAR
WHERE YEAR(EffectiveDate) =2016