是否可以在使用MySQL AVG函数时排除含有0的记录?

是否可以在使用MySQL AVG函数时排除含有0的记录?

若要排除含有“0”的记录,您需要在AVG()函数中使用NULLIF()函数。

语法如下:

SELECT AVG(NULLIF(yourColumnName, 0)) AS anyAliasName FROM yourTableName;

让我们首先创建一个表。

mysql> create table AverageDemo
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > StudentName varchar(20),
   - > StudentMarks int
   - > );
Query OK, 0 rows affected (0.72 sec)

使用insert命令向表中插入一些记录。

查询如下:

mysql> insert into AverageDemo(StudentName,StudentMarks) values('Adam',NULL);
Query OK, 1 row affected (0.12 sec)
mysql> insert into AverageDemo(StudentName,StudentMarks) values('Larry',23);
Query OK, 1 row affected (0.19 sec)
mysql> insert into AverageDemo(StudentName,StudentMarks) values('Mike',0);
Query OK, 1 row affected (0.20 sec)
mysql> insert into AverageDemo(StudentName,StudentMarks) values('Sam',45);
Query OK, 1 row affected (0.18 sec)
mysql> insert into AverageDemo(StudentName,StudentMarks) values('Bob',0);
Query OK, 1 row affected (0.12 sec)
mysql> insert into AverageDemo(StudentName,StudentMarks) values('David',32);
Query OK, 1 row affected (0.18 sec)

使用select语句显示表中所有记录。

查询如下:

mysql> select *from AverageDemo;

以下是输出结果

+----+-------------+--------------+
| Id | StudentName | StudentMarks |
+----+-------------+--------------+
|  1 | Adam        |         NULL |
|  2 | Larry       |           23 |
|  3 | Mike        |            0 |
|  4 | Sam         |           45 |
|  5 | Bob         |            0 |
|  6 | David       |           32 |
+----+-------------+--------------+
一共6行 (0.00 sec)

以下是在使用AVG时排除含有“0”的记录的查询。

mysql> select AVG(nullif(StudentMarks, 0)) AS Exclude0Avg from AverageDemo;

以下是输出结果

+-------------+
| Exclude0Avg |
+-------------+
| 33.3333     |
+-------------+
一共1行 (0.05 sec)

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程