Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I select AVG of multiple columns on a single row

Tags:

sql

mysql

How can I select average of multiple columns?

Suppose I have some data like:

X   Y    Z
-------------
6   3    3
5   5    NULL
4   5    6
11  7    8

I want to get something like

AVG
-------------
4
5
5
8.66666667

I tried select avg(x, y, z) from table

But it doesn't work.

Any ideas on a query to do that?

like image 578
Sinan Avatar asked Dec 10 '22 12:12

Sinan


1 Answers

Try

 Select     (Coalesce(x,0) + Coalesce(y,0) + Coalesce(z,0)) /
       (Coalesce(x/x, 0) + Coalesce(y/y, 0) + Coalesce(z/z, 0))

or

 Select (Coalesce(x,0) + Coalesce(y,0) + Coalesce(z,0)) /
         (Case When x Is Null 0 Else 1 End +
          Case When y Is Null 0 Else 1 End +
          Case When z Is Null 0 Else 1 End)
like image 119
Charles Bretana Avatar answered Jan 15 '23 22:01

Charles Bretana