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

นับเงื่อนไขหลายอย่าง แสดงผลแยกคอลัมน์ใน MySQL ด้วย SUM(CASE...)

เมื่อต้องการนับจำนวนแถวตามเงื่อนไขหลายเงื่อนไข และแสดงผลลัพธ์แยกเป็นคอลัมน์ต่างๆ (Pivot/Crosstab) ให้ใช้ SUM(CASE WHEN ... THEN 1 ELSE 0 END) ร่วมกับ GROUP BY

ตัวอย่างการใช้งาน

สร้างตารางนักเรียน-วิชา:

mysql> create table DemoTable1485 (
    StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    StudentName varchar(20),
    StudentSubject varchar(20)
);
mysql> insert into DemoTable1485(StudentName,StudentSubject) values('Chris','MySQL'),('Robert','MongoDB'),('Robert','MongoDB'),('Chris','Java');

ข้อมูล:

+-----------+-------------+----------------+
| StudentId | StudentName | StudentSubject |
+-----------+-------------+----------------+
| 1         | Chris       | MySQL          |
| 2         | Robert      | MongoDB        |
| 3         | Robert      | MongoDB        |
| 4         | Chris       | Java           |
+-----------+-------------+----------------+

คำสั่งนับจำนวนวิชาต่อคน แสดงแยกคอลัมน์

mysql> select StudentSubject,
    -> sum(case when StudentName = 'Chris' THEN 1 ELSE 0 END) Chris_Count,
    -> sum(case when StudentName = 'Robert' THEN 1 ELSE 0 END) Robert_Count
    -> from DemoTable1485
    -> group by StudentSubject;

ผลลัพธ์

+----------------+-------------+--------------+
| StudentSubject | Chris_Count | Robert_Count |
+----------------+-------------+--------------+
| MySQL          | 1           | 0            |
| MongoDB        | 0           | 2            |
| Java           | 1           | 0            |
+----------------+-------------+--------------+

คำอธิบาย:

  • CASE WHEN condition THEN 1 ELSE 0 END แปลงเงื่อนไขเป็น 1/0
  • SUM(...) รวมค่า 1/0 = จำนวนแถวที่ตรงเงื่อนไข
  • GROUP BY StudentSubject แยกกลุ่มตามวิชา
  • รูปแบบนี้เรียกว่า Conditional Aggregation ทำ Pivot table ได้ใน SQL โดยตรง
  • MySQL 8.0+ รองรับ COUNT(*) FILTER (WHERE condition) แบบมาตรฐาน SQL ได้อีกวิธีหนึ่ง