在MySQL查询中获得水平平均值的最有效方法是什么?

时间:2010-01-31 22:49:06

标签: sql mysql average

我有以下MySQL表

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

编辑:当然,默认情况下该表不需要为NULL,但我不希望它影响平均值(因此平均值计算为50而不是33,33 )。

我希望看起来像这样,使用MySQL查询:

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

实现这一目标的最有效方法是什么?

3 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:3)

如果没有NULL值,下面显而易见的选项会起作用:

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

但是,正如jxac在另一个答案中所建议的那样,你必须按照以下方式进行:

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。

答案 2 :(得分:2)

使用:

  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

参考: