การนับจำนวนการปรากฏของค่าที่ไม่ซ้ำกันด้วย GROUP BY
ใช้ GROUP BY ร่วมกับ COUNT(*) เพื่อได้ค่าที่ไม่ซ้ำ (DISTINCT) พร้อมจำนวนครั้งที่ปรากฏ
ไวยากรณ์
SELECT yourColumn, COUNT(*) AS count
FROM yourTableName
GROUP BY yourColumn;
ตัวอย่างการใช้งาน
สร้างตาราง:
CREATE TABLE selectDistinct_CountDemo (
Id INT NOT NULL AUTO_INCREMENT,
Name VARCHAR(10),
AppearanceId INT,
PRIMARY KEY(Id)
);
เพิ่มข้อมูล (Larry ปรากฏ 4 ครั้ง):
INSERT INTO selectDistinct_CountDemo(Name, AppearanceId) VALUES('Larry', 1);
INSERT INTO selectDistinct_CountDemo(Name, AppearanceId) VALUES('John', 2);
INSERT INTO selectDistinct_CountDemo(Name, AppearanceId) VALUES('Larry', 3);
INSERT INTO selectDistinct_CountDemo(Name, AppearanceId) VALUES('Larry', 10);
INSERT INTO selectDistinct_CountDemo(Name, AppearanceId) VALUES('Carol', 11);
INSERT INTO selectDistinct_CountDemo(Name, AppearanceId) VALUES('Larry', 15);
นับจำนวนครั้งต่อชื่อ:
SELECT Name, COUNT(*) AS TotalAppearance
FROM selectDistinct_CountDemo
GROUP BY Name;
ผลลัพธ์:
+-------+-----------------+
| Name | TotalAppearance |
+-------+-----------------+
| Larry | 4 |
| John | 1 |
| Carol | 1 |
+-------+-----------------+
การขยาย: หลายคอลัมน์
SELECT Name, Age, COUNT(*) AS cnt
FROM table
GROUP BY Name, Age;
การขยาย: เรียงลำดับตามจำนวน
SELECT Name, COUNT(*) AS cnt
FROM table
GROUP BY Name
ORDER BY cnt DESC;
การขยาย: กรองกลุ่มที่มีจำนวนมากกว่า N (HAVING)
SELECT Name, COUNT(*) AS cnt
FROM table
GROUP BY Name
HAVING COUNT(*) > 1; -- เฉพาะชื่อที่ซ้ำ
DISTINCT vs GROUP BY
| คำสั่ง | ผลลัพธ์ | ใช้เมื่อไหร่ |
|---|---|---|
| SELECT DISTINCT col | รายการค่าที่ไม่ซ้ำ | ต้องการแค่รายการ |
| SELECT col, COUNT(*) ... GROUP BY col | ค่าที่ไม่ซ้ำ + จำนวน | ต้องการนับจำนวน |
ประสิทธิภาพ
- สร้าง Index บนคอลัมน์ที่ GROUP BY เพื่อเร่งความเร็ว
- หลีกเลี่ยง SELECT * กับ GROUP BY (บาง version error / non-deterministic)
- MySQL 8.0+ รองรับ Window Functions:
COUNT(*) OVER (PARTITION BY Name)