ใช้ CASE WHEN ภายใน SUM() เพื่อนับเงื่อนไขต่างๆ ของคอลัมน์ต่างกันใน Query เดียว
ตัวอย่าง: นับสี "Red" และสถานะ "New"
1. สร้างตารางและข้อมูล
mysql> create table CountDifferentDemo (
-> ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> ProductName varchar(20),
-> ProductColor varchar(20),
-> ProductDescription varchar(20)
-> );
mysql> insert into CountDifferentDemo(ProductName,ProductColor,ProductDescription) values
-> ('Product-1','Red','Used'),
-> ('Product-1','Blue','Used'),
-> ('Product-2','Green','New'),
-> ('Product-2','Blue','New'),
-> ('Product-3','Green','New'),
-> ('Product-4','Blue','Used');
2. Query นับสองเงื่อนไข
mysql> select ProductName,
-> SUM(CASE WHEN ProductColor = 'Red' THEN 1 ELSE 0 END) AS Color_Red_Count,
-> SUM(CASE WHEN ProductDescription = 'New' THEN 1 ELSE 0 END) AS Desc_New_Count
-> from CountDifferentDemo
-> group by ProductName;
3. ผลลัพธ์
+-------------+-----------------+----------------+ | ProductName | Color_Red_Count | Desc_New_Count | +-------------+-----------------+----------------+ | Product-1 | 1 | 0 | | Product-2 | 0 | 2 | | Product-3 | 0 | 1 | | Product-4 | 0 | 0 | +-------------+-----------------+----------------+
รูปแบบอื่น: ใช้ COUNT กับเงื่อนไข
SELECT
ProductName,
COUNT(CASE WHEN ProductColor = 'Red' THEN 1 END) AS Color_Red_Count,
COUNT(CASE WHEN ProductDescription = 'New' THEN 1 END) AS Desc_New_Count
FROM CountDifferentDemo
GROUP BY ProductName;
หมายเหตุ: COUNT นับเฉพาะค่า non-NULL ดังนั้น ELSE NULL จะไม่นับ
MySQL 8.0+ ใช้ FILTER clause (ไม่รองรับโดยตรง แต่สามารถจำลองได้)
-- PostgreSQL style (MySQL ไม่รองรับ FILTER) -- COUNT(*) FILTER (WHERE ProductColor = 'Red') -- MySQL equivalent: SUM(ProductColor = 'Red') -- TRUE = 1, FALSE = 0
ขยายเป็นหลายเงื่อนไข
SELECT
ProductName,
SUM(ProductColor = 'Red') as red_count,
SUM(ProductColor = 'Blue') as blue_count,
SUM(ProductColor = 'Green') as green_count,
SUM(ProductDescription = 'New') as new_count,
SUM(ProductDescription = 'Used') as used_count
FROM CountDifferentDemo
GROUP BY ProductName;