I saw this answer how do I select AVG of multiple columns on a single row but I have some rows which is the value is 0 and it’s throwing an error division by zero
when I try to use his
select (COALESCE(q1,0)+COALESCE(q2,0)+COALESCE(q3,0)+COALESCE(q4,0) / (COALESCE(q1/q1,0)+COALESCE(q2/q2,0)+COALESCE(q3/q3,0)+COALESCE(q4/q4,0) from table1
ex.
q1 q2 q3 q4
10 5 NULL 0
8 5 5 NULL
5 5 5 5
--------------
7.5
6
5
3
Answers
you are qualescing q4/q4 which is 0/0
i gave it a try and this is the query that worked, converting the value to bool first (true/false) and then converting that to an int is the safer option if you expect a lot of null and zero values:
In order to resolve the task, you can use
CASE
expression because you cannot divide by zero:dbfiddle
It is added extra
COALESCE
because the sum of the divisor can be zero as wellYou can turn the columns into rows then use
avg()
as an aggregate on those rows:alternatively this can be expressed with a lateral cross join:
Instead of using
avg (x.val) filter(...)
you can also useavg(nullif(x.val,0))