我如何计算字段的平均值并排除 0 值

How can i calculate the average of fields and exclude the 0 values

我有这个:

SELECT
    ROUND(AVG(coffee)) 'coffee',
    ROUND(AVG(cappucino)) 'cappucino',
    ROUND(AVG(espresso)) 'espresso',
    ROUND(AVG(machine)) 'machine'
    FROM `reviews` ORDER BY `username`

我的 Table 看起来像:

+-----+-----------+---------------+---------------+---------------+---------------+
| id  | name      | coffee        | cappucino     | espresso      | machine       |
+-----+-----------+---------------+---------------+---------------+---------------+
|  1  | Joe       | 5             | 4             | 5             | 4             |
|  2  | Jane      | 3             | 5             | 2             | 5             |
|  3  | Mike      | 0             | 0             | 0             | 5             |
+-----+-----------+---------------+---------------+---------------+---------------+

我需要评论的平均值,但迈克不喝咖啡,他点击了“不适用”按钮。所以目前的平均值是:

coffee 2.66666667
cappucino 3
espresso 2.33333333
machine 4.66666667

但应该是:

coffee 4
cappucino 4.5
espresso 3.5
machine 4.66666667

我该如何解决这个问题?

AVG 会忽略 NULL 值,AVG(NULLIF(coffee,0)) 也是如此。或者首先存储 NULL 而不是 0。

这绝对是个好问题。我想出了一个解决方案。

 select avg(coffee) from data where coffee>0 union select avg(cappucino) from data where cappucino >0 union select avg(expresso) from data where expresso>0 union select avg(machine) from data where machine>0;

试试这个。我使用字段中的值应大于 0 的 where 条件分别计算所有字段的平均值,然后显示所有查询的 UNION。

这将是输出...为了避免将 avg(coffee) 作为列 header,您可以使用 ALIAS。

+-------------+
| avg(coffee) |
+-------------+
|      4.0000 |
|      4.5000 |
|      3.5000 |
|      4.6667 |
+-------------+

希望对您有所帮助。

这是修复:

SELECT
    ROUND(AVG(NULLIF(coffee,0))) 'coffee',
    ROUND(AVG(NULLIF(cappucino,0))) 'cappucino',
    ROUND(AVG(NULLIF(espresso,0))) 'espresso',
    ROUND(AVG(NULLIF(machine,0))) 'machine'
    FROM `reviews` ORDER BY `username`