PostgreSQL:如何避免除以零?
我试图从表 oc_cap 中获取平均占用率,但收到错误“错误:除以零”。两列中的值均为 0。 我一直在考虑使用 NULLIF(column_name,0) 但我不知道如何在下面的代码中实现它。
SELECT *, AVG((occupancy/capacity) * 100)) AS avg_occupancy_rate
FROM occu_cap
GROUP BY 1,2,3
样本数据和预期结果:
占用 | 容量 | avg_occupancy_rate |
---|---|---|
1232 | 1630 | 75.58 |
0 | 658 | null |
0 | 0 | null |
I am trying to get the average occupation rate from table occu_cap but I am getting the error "ERROR: division by zero". There are 0 values in both columns.
I've been looking at using NULLIF(column_name,0) but I can't figure out how to implement this into the code below.
SELECT *, AVG((occupancy/capacity) * 100)) AS avg_occupancy_rate
FROM occu_cap
GROUP BY 1,2,3
Sample data and expected result:
occupancy | capacity | avg_occupancy_rate |
---|---|---|
1232 | 1630 | 75.58 |
0 | 658 | null |
0 | 0 | null |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该错误是由于
capacity
为0
值(这可能不允许数学除法)引起的,如果您的预期结果是0
时capacity
is0
fromocpancy/capacity
Edit
可以尝试使用
CASE WHEN
表达式来判断值是否为零则返回NULL
如果如果你想显示所有的列,你可以尝试使用窗口函数。
注意
如果您的
占用
或容量
不是浮点数类型,我们需要CAST
将其转换为执行AVG
之前的浮点数sqlfiddle
The error was caused that
capacity
was0
value (which might not allow from math divide), if your expected result is0
whencapacity
is0
fromoccupancy/capacity
Edit
You can try to use
CASE WHEN
expression to judge the value whether zero then returnNULL
If you want to show all of columns you can try to use the window function.
NOTE
If your
occupancy
orcapacity
is not a type of a float-point number we need toCAST
that as a float-point number before doingAVG
sqlfiddle