[英]bigQuery throws “division by zero: 0 / 0” error
I am doing the percentage by the frequency of column value using bigquery.我正在使用 bigquery 按列值的频率计算百分比。 However, some of the value might be zero, so the query will return error for sure但是,某些值可能为零,因此查询肯定会返回错误
(division by zero: 0 / 0)
How to apply kind of IFERROR(x/y,null) in this case?在这种情况下如何应用一种 IFERROR(x/y,null) ? so the query will bounce null value as the result instead of error?所以查询将返回 null 值作为结果而不是错误?
SELECT
User_ID,
ROUND(SUM(CASE WHEN Name LIKE '%MIKE%' THEN 1 ELSE 0 END) / COUNT(Name) * 100 ,1) AS Percentage_of_MIKE,
FROM
table
GROUP BY
User_ID
TRIED:试过:
ROUND(SAFE_DIVIDE(SUM(CASE WHEN Name LIKE '%MIKE%' THEN 1 ELSE 0 END) / COUNT(Name) * 100 ,1)) AS Percentage_of_MIKE,
You can just use SAFE_DIVIDE function in such cases在这种情况下,您可以只使用SAFE_DIVIDE function
Something like in below example像下面的例子
ROUND(SAFE_DIVIDE(SUM(CASE WHEN Name LIKE '%MIKE%' THEN 1 ELSE 0 END), COUNT(Name) * 100) ,1) AS Percentage_of_MIKE
This error indicates that you have User_ID
s whose all Name
s are NULL
.此错误表明您有User_ID
,其所有Name
都是NULL
。 So the denominator of your division is 0
( COUNT(Name)
counts non- null
values of Name
), and you get the division by 0
error.因此,除法的分母为0
( COUNT(Name)
计算Name
的非null
值),并且除以0
错误。
A simple way to avoid this is to use AVG()
:避免这种情况的一种简单方法是使用AVG()
:
ROUND(AVG(CASE
WHEN Name LIKE '%MIKE%' THEN 1.0
WHEN Name IS NOT NULL THEN 0
END) * 100, 1) AS Percentage_of_MIKE
I tend to use NULLIF()
for this purpose, because I like using the division operator for division:为此,我倾向于使用NULLIF()
,因为我喜欢使用除法运算符进行除法:
SELECT User_ID,
ROUND(COUNTIF(Name LIKE '%MIKE%') * 100 / NULLIF(COUNT(Name), 0), 1) AS Percentage_of_MIKE
FROM table
GROUP BY User_ID;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.