[英]Avoid division by zero in PostgreSQL
I'd like to perform division in a SELECT clause.我想在 SELECT 子句中执行除法。 When I join some tables and use aggregate function I often have either null or zero values as the dividers.
当我加入一些表并使用聚合函数时,我经常使用空值或零值作为分隔符。 As for now I only come up with this method of avoiding the division by zero and null values.
至于现在我只提出了这种避免除以零和空值的方法。
(CASE(COALESCE(COUNT(column_name),1)) WHEN 0 THEN 1
ELSE (COALESCE(COUNT(column_name),1)) END)
I wonder if there is a better way of doing this?我想知道是否有更好的方法来做到这一点?
Since count()
never returns NULL
(unlike other aggregate functions), you only have to catch the 0
case (which is the only problematic case anyway).由于
count()
从不返回NULL
(与其他聚合函数不同),因此您只需捕获0
情况(无论如何这是唯一有问题的情况)。 So, your query simplified:因此,您的查询简化了:
CASE count(column_name)
WHEN 0 THEN 1
ELSE count(column_name)
END
Or simpler, yet, with NULLIF()
, like Yuriy provided .或者更简单,但是,使用
NULLIF()
,就像 Yuriy 提供的一样。
Quoting the manual about aggregate functions: 引用有关聚合函数的手册:
It should be noted that except for
count
, these functions return a null value when no rows are selected.需要注意的是,除了
count
之外,当没有选择任何行时,这些函数返回一个空值。
I realize this is an old question, but another solution would be to make use of the greatest function:我意识到这是一个老问题,但另一个解决方案是利用最大的功能:
greatest( count(column_name), 1 ) -- NULL and 0 are valid argument values
Note: My preference would be to either return a NULL, as in Erwin and Yuriy's answer, or to solve this logically by detecting the value is 0
before the division operation, and returning 0
.注意:我的偏好是要么返回 NULL,如 Erwin 和 Yuriy 的回答,要么通过在除法运算之前检测值是
0
并返回0
来逻辑地解决这个问题。 Otherwise, the data may be misrepresented by using 1
.否则,数据可能会因使用
1
而被歪曲。
避免除以零的另一种解决方案,替换为1
select column + (column = 0)::integer;
If you want the divider to be 1 when the count is zero:如果您希望在计数为零时分频器为 1:
count(column_name) + 1 * (count(column_name) = 0)::integer
The cast from true
to integer
is 1.从
true
到integer
为 1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.