使用MySQL AVG函式時,我們可以排除帶有“0”的條目嗎?


要排除帶有“0”的條目,你需要將 NULLIF() 與 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
   - > );
Query OK, 0 rows affected (0.72 sec)

使用插入命令在表中插入一些記錄。

查詢如下

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 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)

更新日期:30-Jul-2019

4k+瀏覽

開啟你的職業生涯

完成該課程獲取認證

開始
廣告
© . All rights reserved.