Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

นับจำนวนนักเรียน Present และ Absent ต่อปีใน MySQL

ใช้ IF() ร่วม SUM() นับเงื่อนไขแยกตามปี

สร้างตารางและเพิ่มข้อมูล

mysql> create table DemoTable1617 ( Attendance varchar(20), CurrentYear int ); 
Query OK, 0 rows affected (0.48 sec)
mysql> insert into DemoTable1617 values('Present',2019); 
Query OK, 1 row affected (0.15 sec) 
mysql> insert into DemoTable1617 values('Absent',2019); 
Query OK, 1 row affected (0.20 sec) 
mysql> insert into DemoTable1617 values('Absent',2017); 
Query OK, 1 row affected (0.13 sec) 
mysql> insert into DemoTable1617 values('Present',2019); 
Query OK, 1 row affected (0.15 sec) 
mysql> insert into DemoTable1617 values('Present',2018); 
Query OK, 1 row affected (0.10 sec) 
mysql> insert into DemoTable1617 values('Present',2019); 
Query OK, 1 row affected (0.14 sec)

คิวรี่นับ Present และ Absent ปี 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%';

ผลลัพธ์

+---------+--------+ 
| Present | Absent | 
+---------+--------+ 
|       3 |      1 | 
+---------+--------+ 
1 row in set (0.00 sec)

เทคนิค: IF(condition, 1, 0) คืน 1 เมื่อตรงเงื่อนไข 0 เมื่อไม่ตรง | SUM รวมค่า 1/0 = จำนวนที่ตรง | ใช้ได้กับเงื่อนไขหลายแบบในคิวรี่เดียว