sql - Division gives values 0 -


in order avoid division 0 using cast float , nullif. reason gives me values 0. doing dividing declined on submissions doing wrong?

select          [status reason],                 b.monthnum,                 b.yearnum,                 isnull(sum(case when  status = 'declined' 1 else 0 end ),0)  declined,                 (                     select  count(controlno)                         clearancereportmetrics                        year(effectivedate) =year(getdate())  , companyline = 'ironshore insurance company'                      , lineofbusiness not in ('ssp commercial general liability','ssp property') , underwriter <> 'batcheller, jerry'                 ) submissions,          /*and gives 0's  */                  coalesce(cast(sum(case when  status = 'declined' 1 else 0 end ) float) /                 (           /* here using nullif avoid division 0 */                     select  nullif(count(controlno),0)                         clearancereportmetrics                        effectivedate =year(getdate())  , companyline = 'ironshore insurance company'                              , lineofbusiness not in ('ssp commercial general liability','ssp property') , underwriter <> 'batcheller, jerry'                 ),0) declinedratio         tblcalendar b left join   clearancereportmetrics on b.monthnum = month(a.effectivedate) , b.yearnum = year(a.effectivedate)                  --and   effectivedate >=dateadd(yy, -1, dateadd(d, 1, eomonth(getdate()))) , effectivedate <= eomonth(getdate())  , companyline = 'ironshore insurance company' , status = 'declined'                 --and lineofbusiness not in ('ssp commercial general liability','ssp property')        b.yearnum = year(getdate()) group    b.yearnum,b.monthnum,[status reason] order    b.yearnum, b.monthnum   ,declined desc 

enter image description here

here 1 way solve it, , make query easier read (removes nasty duplication of code calculates declines , submissions).

example using dummy inner data. move ratio calculation outer query.

select    x.*   ,case        when submissions > 0        cast(declined float) / submissions        else null    end declinedratio (     -- dummy data, replace existing query (except ratio calculation).     select            'does not meet underwriting guidelines' [status reason]           ,1 monthnum           ,2016 yearnum           ,5 declined           ,10 submissions ) x; 

assumption, declines never exceed submissions.

i think may better return null in "divide 0" case rather 0, 0 genuine result.


Comments