在case语句中避免除以零错误

时间:2014-07-02 14:37:14

标签: sql

我的脚本中出现了零除错误。 任何人都可以帮忙。

我试图划分两条记录,其中一条记录为零。我不想失去这一排,请告知。

select DATEPART(Year,Request_date) as "Year",
       DATEPART(Month,Request_date) as "Month",
       COUNT([MONTH_OF_SUSPENSION]) as "Request" ,
       sum(case when [PAYMENT_<=24HRS] = 'Y' then 1 else 0 end) as "Paid in 24hrs",   
       COUNT([MONTH_OF_SUSPENSION])/sum(case when [PAYMENT_<=24HRS] = 'Y' then 1 else 0 end) as "Achieved"
FROM suspension_br
  where REQUEST_STATUS = 'OTHERS'
GROUP BY DATEPART(Year,Request_date),DATEPART(Month,Request_date)

3 个答案:

答案 0 :(得分:1)

您可以引入第二个case来检查sum的结果:

case
when sum(case when [PAYMENT_<=24HRS] = 'Y' then 1 else 0 end) > 0
then COUNT([MONTH_OF_SUSPENSION])/sum(case when [PAYMENT_<=24HRS] = 'Y' then 1 else 0 end)
else 0 /* a default value that makes sense to you */
end as "Achieved"

答案 1 :(得分:1)

查看您的代码我可以假设您正在使用MSSQL,因此如果两个参数相等,您可以使用nullif返回null。例如,您的代码可能如下所示:

COUNT([MONTH_OF_SUSPENSION])/nullif(sum(case when [PAYMENT_<=24HRS] = 'Y' then 1 else 0 end),0) as "Achieved"

它做的是,如果sum运算符的值等于0,则除数从零变为null,这将导致整个等式变为{{ 1}}。

答案 2 :(得分:0)

使用另一个案例陈述来检查总和的结果

select DATEPART(Year,Request_date) as "Year",
       DATEPART(Month,Request_date) as "Month",
       COUNT([MONTH_OF_SUSPENSION]) as "Request" ,
       sum(case 
             when [PAYMENT_<=24HRS] = 'Y' then 1 
             else 0 
           end) as "Paid in 24hrs",   
       case 
         when sum(case 
                    when [PAYMENT_<=24HRS] = 'Y' then 1 
                    else 0 
                  end) = 0 then 'whatever you want in this case' 
         else COUNT([MONTH_OF_SUSPENSION])/sum(case 
                                                 when [PAYMENT_<=24HRS] = 'Y' then 1  
                                                 else 0 
                                               end) as "Achieved"
FROM suspension_br
  where REQUEST_STATUS = 'OTHERS'
GROUP BY DATEPART(Year,Request_date),DATEPART(Month,Request_date)

虽然看起来很讨厌,所以你可以通过子选择整理一下:

select 
  year, 
  month, 
  request, 
  PaidIn24hrs, 
  case
    when PaidIn24hrs = 0 then 'whatever you want in this case'
    else request/PaidIn24hrs
  end as "Achieved"
from 
(
    select DATEPART(Year,Request_date) as "Year",
           DATEPART(Month,Request_date) as "Month",
           COUNT([MONTH_OF_SUSPENSION]) as "Request" ,
           sum(case 
                 when [PAYMENT_<=24HRS] = 'Y' then 1 
                 else 0 
               end) as "PaidIn24hrs"
    FROM suspension_br
      where REQUEST_STATUS = 'OTHERS'
    GROUP BY DATEPART(Year,Request_date),DATEPART(Month,Request_date)
)