Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Loại trừ giá trị 0 khi dùng hàm AVG trong MySQL

Để loại trừ các giá trị 0 khi tính trung bình, kết hợp NULLIF() với AVG().

Cú pháp:

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

Tạo bảng:

mysql> CREATE TABLE AverageDemo (
    -> Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> StudentName VARCHAR(20),
    -> StudentMarks INT
    -> );

Chèn dữ liệu (có giá trị NULL và 0):

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

Hiển thị dữ liệu:

+----+-------------+--------------+
| Id | StudentName | StudentMarks |
+----+-------------+--------------+
|  1 | Adam        | NULL         |
|  2 | Larry       | 23           |
|  3 | Mike        | 0            |
|  4 | Sam         | 45           |
|  5 | Bob         | 0            |
|  6 | David       | 32           |
+----+-------------+--------------+

Truy vấn loại trừ 0:

mysql> SELECT AVG(NULLIF(StudentMarks, 0)) AS Exclude0Avg FROM AverageDemo;

Kết quả:

+-------------+
| Exclude0Avg |
+-------------+
| 33.3333     |
+-------------+

Lưu ý: NULLIF(col, 0) trả về NULL nếu col = 0, và AVG() tự động bỏ qua NULL.