เพื่อไม่นับค่า 0 ในการคำนวณค่าเฉลี่ย (AVG()) ให้ใช้ฟังก์ชัน NULLIF() แปลงค่า 0 เป็น NULL เนื่องจาก AVG() ข้ามค่า NULL ไปโดยอัตโนมัติ
รูปแบบคำสั่ง
SELECT AVG(NULLIF(yourColumnName, 0)) AS anyAliasName FROM yourTableName;
ตัวอย่างเต็ม
1. สร้างตารางและเพิ่มข้อมูล
mysql> create table AverageDemo (
-> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> StudentName varchar(20),
-> StudentMarks int
-> );
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);
2. ข้อมูลในตาราง
+----+-------------+--------------+ | Id | StudentName | StudentMarks | +----+-------------+--------------+ | 1 | Adam | NULL | | 2 | Larry | 23 | | 3 | Mike | 0 | | 4 | Sam | 45 | | 5 | Bob | 0 | | 6 | David | 32 | +----+-------------+--------------+
3. คำนวณเฉลี่ยไม่นับ 0
mysql> select AVG(nullif(StudentMarks, 0)) AS Exclude0Avg from AverageDemo;
+-------------+ | Exclude0Avg | +-------------+ | 33.3333 | +-------------+
การคำนวณ
- ค่าที่นับ: 23, 45, 32 (ไม่นับ NULL และ 0)
- ผลรวม: 100
- จำนวน: 3
- ค่าเฉลี่ย: 100/3 = 33.3333
เทคนิคเพิ่มเติม
หากต้องการตัดค่าอื่นๆ ออก ให้เปลี่ยนค่าใน NULLIF(column, value_to_exclude) เช่น NULLIF(score, -1) เพื่อตัด -1 ออก