I have a table where I want to find the average value of column1 and column2, but in some cases there may be null values in either columns. In that case, I just want to be shown the value that is NOT null.
Example:
Column1 | Column2 |
---|---|
10 | Null |
9 | 15 |
So in this case I want to see:
Column3 |
---|
10 |
12 |
I’m still a beginner so my knowledge is pretty limited, also I want to keep it as simple as possible. I’m using phpmyadmin if that makes any difference.
I’ve tried sum(table1+table2)/2
which results in null if one of the values is null.
I’ve also tried
SELECT
CASE
WHEN table2 IS null
THEN SUM(table1)
ELSE SUM(table1+table2)/2
END
but it just returns the average of rows where there isn’t a null value (I only get back 12, not the 10 as well (refer to the above table))
2
Answers
SUM
is for summing values over multiple rows. Here, you just want simple math and replacing nulls with 0 and counting non-nullsYou are near with the case expression.
There is no need for sum and you have not considered null for column1 .
Fixing those, the query would be :
See example