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 |
The error was caused that
capacitywas0value (which might not allow from math divide), if your expected result is0whencapacityis0fromoccupancy/capacityEdit
You can try to use
CASE WHENexpression to judge the value whether zero then returnNULLIf you want to show all of columns you can try to use the window function.
NOTE
If your
occupancyorcapacityis not a type of a float-point number we need toCASTthat as a float-point number before doingAVGsqlfiddle