4

我有一个简单的表(测试),我需要在其中执行一些平均值(我想获得行平均值和“总”列平均值)。

 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

4 回答 4

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
于 2013-07-04T13:01:05.207 回答
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()功能。

玩得开心!

于 2013-07-04T12:48:43.563 回答
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
于 2013-07-04T12:51:15.440 回答
0

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

于 2013-07-04T12:50:44.867 回答