要排除带有“ 0”的条目,您需要使用NULLIF()
function AVG()
。
语法如下
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 - > );
使用insert命令在表中插入一些记录。
查询如下
mysql> insert into AverageDemo(StudentName,StudentMarks) values('Adam',NULL); mysql> insert into AverageDemo(StudentName,StudentMarks) values('Larry',23); mysql> insert into AverageDemo(StudentName,StudentMarks) values('Mike',0); mysql> insert into AverageDemo(StudentName,StudentMarks) values('Sam',45); mysql> insert into AverageDemo(StudentName,StudentMarks) values('Bob',0); mysql> insert into AverageDemo(StudentName,StudentMarks) values('David',32);
使用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 rows in set (0.00 sec)
以下是在使用AVG时排除具有“ 0”的条目的查询
mysql> select AVG(nullif(StudentMarks, 0)) AS Exclude0Avg from AverageDemo;
以下是输出
+-------------+ | Exclude0Avg | +-------------+ | 33.3333 | +-------------+ 1 row in set (0.05 sec)