PostgreSQL:如何避免除以零?

发布于 2025-01-20 07:33:10 字数 854 浏览 6 评论 0原文

我试图从表 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
1232163075.58
0658null
00null

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:

occupancycapacityavg_occupancy_rate
1232163075.58
0658null
00null

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小ぇ时光︴ 2025-01-27 07:33:10

该错误是由于 capacity0 值(这可能不允许数学除法)引起的,如果您的预期结果是 0capacity is 0 from ocpancy/capacity

AVG((COALESCE(occupancy / NULLIF(capacity,0), 0) * 100))

Edit

可以尝试使用CASE WHEN表达式来判断值是否为零则返回NULL

AVG(CASE WHEN capacity <> 0 AND occupancy <> 0 THEN ((occupancy::decimal/capacity * 1.0) * 100) END)

如果如果你想显示所有的列,你可以尝试使用窗口函数。

SELECT *,AVG(CASE WHEN capacity <> 0 AND occupancy <> 0 THEN ((occupancy::decimal/capacity * 1.0) * 100) END) OVER(PARTITION BY id)
FROM occu_cap

注意

如果您的占用容量不是浮点数类型,我们需要CAST将其转换为执行 AVG 之前的浮点数

sqlfiddle

The error was caused that capacity was 0 value (which might not allow from math divide), if your expected result is 0 when capacity is 0 from occupancy/capacity

AVG((COALESCE(occupancy / NULLIF(capacity,0), 0) * 100))

Edit

You can try to use CASE WHEN expression to judge the value whether zero then return NULL

AVG(CASE WHEN capacity <> 0 AND occupancy <> 0 THEN ((occupancy::decimal/capacity * 1.0) * 100) END)

If you want to show all of columns you can try to use the window function.

SELECT *,AVG(CASE WHEN capacity <> 0 AND occupancy <> 0 THEN ((occupancy::decimal/capacity * 1.0) * 100) END) OVER(PARTITION BY id)
FROM occu_cap

NOTE

If your occupancy or capacity is not a type of a float-point number we need to CAST that as a float-point number before doing AVG

sqlfiddle

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文