MySQL中的行平均值 - 如何从计数中排除NULL行

时间:2013-07-04 12:46:39

标签: mysql sql

我有简单的表格(测试),我需要执行一些平均值(我想得到行平均值和'总'列平均值。)

 id  var1  var2  var3
 1   7     NULL  3
 2   10    NULL  6

我注意到MySQL AVG()函数从计数中排除了NULL值(它们不算作0),这就是我想要的。

以类似的方式,我想要这个结果:

var1 var2  var3 total
8.5  NULL  4.5  6.5   (i.e. the overall average is 6.5 *not* 4.3333)

但我的查询如下:

SELECT
AVG(var1) AS var1,
AVG(var2) AS var2,
AVG(var3) AS var3,
(
 AVG(var1)+ 
 AVG(var2)+
 AVG(var3)
)/3.0 AS metric_total
FROM test

返回总平均值4.333。

是否可以在单个查询中获得行计算,以与AVG()函数相同的方式从计数中排除NULL条目?

4 个答案:

答案 0 :(得分:3)

这个怎么样?好又简单......

SELECT
AVG(var1) AS var1,
AVG(var2) AS var2,
AVG(var3) AS var3,
(
 SUM(ifnull(var1,0))+
 SUM(ifnull(var2,0))+
 SUM(ifnull(var3,0))
) / (COUNT(var1)+COUNT(var2)+COUNT(var3))
 AS metric_total
FROM test

答案 1 :(得分:2)

SELECT
    avg1, avg2, avg3,
    ( 
      (COALESCE(avg1, 0) + COALESCE(avg2, 0) + COALESCE(avg3, 0)) -- only add non-null values
      / -- division
      ( IF(avg1 IS NULL, 0, 1) + IF(avg2 IS NULL, 0, 1) + IF(avg3 IS NULL, 0, 1) ) -- number of non-null averages
    ) AS metric_total
FROM
    ( SELECT
        (SELECT AVG(var1) FROM test) AS avg1,
        (SELECT AVG(var2) FROM test) AS avg2,
        (SELECT AVG(var3) FROM test) AS avg3
    ) AS sub

子查询只允许不重复AVG()函数。

Have fun!

答案 2 :(得分:1)

您想要所有列的var1,var2和var3的平均值。也许为每列做一个子选择以得到它的平均值,每个子选择联合在一起。如果每列具有相同数量的非空字段

,则此方法仅起作用
SELECT AVG(FirstAvg)
FROM
(
    SELECT AVG(var1) AS FirstAvg
    FROM test
    UNION
    SELECT AVG(var2) AS FirstAvg
    FROM test
    UNION
    SELECT AVG(var3) AS FirstAvg
    FROM test
) Sub1

要修复该问题,可以在子选择上执行一次AVG

SELECT AVG(FirstAvg)
FROM
(
    SELECT var1 AS FirstAvg
    FROM test
    UNION
    SELECT var2 AS FirstAvg
    FROM test
    UNION
    SELECT var3 AS FirstAvg
    FROM test
) Sub1

要获得其他列的平均值: -

SELECT AVG(var1), AVG(var2), AVG(var3), AVG(FirstAvg) AS total
FROM
(
    SELECT var1 AS var1, NULL AS var2, NULL AS var3, var1 AS FirstAvg
    FROM test
    UNION
    SELECT NULL AS var1, var2 AS var2, NULL AS var3, var2 AS FirstAvg
    FROM test
    UNION
    SELECT NULL AS var1, NULL AS var2, var3 AS var3, var3 AS FirstAvg
    FROM test
) Sub1

答案 3 :(得分:0)

而不是AVG(var1), AVG(var2)等尝试使用AVG(ISNULL(var1,0)), AVG(ISNULL(var2,0))