Đếm số lượng Present/Absent theo năm với SUM(IF())
Sử dụng IF() bên trong SUM() để đếm có điều kiện theo từng giá trị cột Attendance.
Tạo bảng và dữ liệu
mysql> create table DemoTable1617 (
Attendance varchar(20),
CurrentYear int
);
Query OK, 0 rows affected (0.48 sec)
mysql> insert into DemoTable1617 values('Present',2019);
mysql> insert into DemoTable1617 values('Absent',2019);
mysql> insert into DemoTable1617 values('Absent',2017);
mysql> insert into DemoTable1617 values('Present',2019);
mysql> insert into DemoTable1617 values('Present',2018);
mysql> insert into DemoTable1617 values('Present',2019);
Truy vấn đếm cho năm 2019
mysql> select sum(if(Attendance='Present',1,0)) as Present,
sum(if(Attendance='Absent',1,0)) as Absent
from DemoTable1617
where CurrentYear LIKE '2019%';
Kết quả
+---------+--------+ | Present | Absent | +---------+--------+ | 3 | 1 | +---------+--------+
Phân tích: Năm 2019 có 4 bản ghi: 3 'Present', 1 'Absent'.
Cách thay thế hiện đại (MySQL 8.0+): Dùng COUNT(*) FILTER (WHERE ...) (chuẩn SQL) hoặc SUM(Attendance='Present') (MySQL cho phép boolean như số 0/1).
SELECT
SUM(Attendance='Present') as Present,
SUM(Attendance='Absent') as Absent
FROM DemoTable1617
WHERE CurrentYear = 2019;
Lưu ý: LIKE '2019%' hoạt động vì CurrentYear là INT, MySQL tự chuyển sang chuỗi. Nên dùng = 2019 cho chính xác và tận dụng index.