What is the most efficient way to get the horizontal average in a MySQL query?

I have the following MySQL table

Id  |  One  |  Two  |  Three
----------------------------
1   |  10   |  30   |  20
2   |  50   |  60   |  20
3   |  60   |  NULL |  40

Edit: Of course, the default for the table should not be NULL, but I do not want it to affect the average value (therefore, the average value is calculated as 50, not 33.33).

I want it to look like this: with a MySQL query:

Id | Average
------------
1  | 20
2  | 43,33
3  | 50

What is the most effective way to achieve this?

+3
source share
3 answers
select id, (ifnull(one,0) + ifnull(two,0) + ifnull(three,0))/
  ((one is not null) + (two is not null) + (three is not null)) as average from table
+9
source

The obvious option below would work if you didn't have NULL values:

SELECT ((col_1 + col_2 + col_3) / 3) AS Average FROM table;

However, as jxac suggested in another answer, you should do it like this:

SELECT id, (ifnull(col_1, 0) + ifnull(col_2, 0) + ifnull(col_3, 0)) /
  ((col_1 is not null) + (col_2 is not null) + (col_3 is not null)) as Average 
FROM
    table;

NULL, NULL .

+3

:

  SELECT a.id,
         AVG(a.val) AS average
    FROM (SELECT x.id,
                 x.one AS val
            FROM TABLE x
          UNION ALL
          SELECT y.id,
                 y.two AS val
            FROM TABLE y
          UNION ALL
          SELECT z.id,
                 z.three AS val
            FROM TABLE z) a
GROUP BY a.id

:

+2
source

Source: https://habr.com/ru/post/1730794/


All Articles