雪花查询中遇到除以零错误

use*_*545 7 snowflake-schema snowflake-cloud-data-platform

我有以下雪花查询,其中出现除以零的错误...您能在这里帮助我吗...

with cte1 as 
(select * from "coe.cup"
where typeofcare ='AM'
and status ='DONE'
and review ='false'
and date (assigneddate)>='2021-04-01'), cte2 as(
select cast(completed as date) completeddate ,iscode
 ,iff(iscode=1,datediff(minute,assigneddate,coded),0) codeddatetime
 ,iff(iscode=0,datediff(minute,assigneddate,qaed),0) qaeddatetime
 ,datediff(minute,assigneddate,completed) overall  from 
 (select *,iff(qaed='1900-01-01 00:00:00.0000000',1,0) iscode from cte1)a )
 select completeddate 
 ,sum(iff(iscode=1,1,0)) noofvisitbillscoded
 ,sum(iff(iscode=1,0,1)) noofvisitbillscodedandqaed
 ,count(1) totalvisitbillscompleted
 ,cast(sum(codeddatetime)/sum(iff(iscode=1,1,0)) as float)/60 averagetimeforcodedvisitbills
 ,cast(sum(qaeddatetime)/sum(iff(iscode=1,0,1)) as float)/60  averagetimeforcodedandqaedvisitbills
 ,cast(sum(overall)/count(1) as float)/60 overallaveragetime
 from cte2
 group by completeddate
Run Code Online (Sandbox Code Playgroud)

Rob*_*ong 2

我认为发生这种情况是因为/sum(iff(iscode=1,1,0))this 有时可能返回 0。

处理被零除的一种方法是使用NULLIF

NULLIF( <expr1> , <expr2> )
Run Code Online (Sandbox Code Playgroud)

NULL如果expr1等于 则返回expr2,否则返回expr1。

因此,在您的代码中,例如sum(iff(iscode=1,1,0)),您可以将其替换为:

NULLIF(sum(iff(iscode = 1, 1, 0)), 0)
Run Code Online (Sandbox Code Playgroud)

然后这应该返回NULL而不是导致被零除。