3

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
jps
  • 20,041
  • 15
  • 75
  • 79
Ben Watson
  • 119
  • 6
  • [DBFIDDLE](https://dbfiddle.uk/?rdbms=postgres_14&fiddle=44f66ade118f754b25520f8e78a34f3f) – Luuk Apr 09 '22 at 10:07

1 Answers1

4

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

D-Shih
  • 44,943
  • 6
  • 31
  • 51
  • Hi, when using your syntax the output is only 0.0000000 for every row. – Ben Watson Apr 09 '22 at 09:43
  • Could you provide some sample data and expcet result? It worked in SQLfiddle https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=b32c2cdbac9bcf2087c7321ec99d06e7 – D-Shih Apr 09 '22 at 09:46