นับความถี่ของค่าที่ซ้ำกันในคอลัมน์
ใช้ COUNT(*) ร่วมกับ GROUP BY เพื่อจับกลุ่มค่าเหมือนกันและนับจำนวน
รูปแบบคำสั่ง (Syntax)
SELECT yourColumnName, COUNT(*) AS count_alias
FROM yourTableName
GROUP BY yourColumnName;
ตัวอย่างการใช้งาน
สร้างตาราง RowWithSameValue:
CREATE TABLE RowWithSameValue (
StudentId INT,
StudentName VARCHAR(100),
StudentMarks INT
);
ข้อมูล (มีคะแนน 89 ซ้ำ 3 คน):
| StudentId | StudentName | StudentMarks |
|---|---|---|
| 100 | Carol | 89 |
| 101 | Sam | 89 |
| 102 | John | 99 |
| 103 | Johnson | 89 |
นับจำนวนนักเรียนแต่ละคะแนน:
SELECT StudentMarks, COUNT(*) AS SameValue
FROM RowWithSameValue
GROUP BY StudentMarks;
ผลลัพธ์:
| StudentMarks | SameValue |
|---|---|
| 89 | 3 |
| 99 | 1 |
การประยุกต์ใช้เพิ่มเติม
1. เรียงลำดับตามจำนวนมากไปน้อย:
SELECT StudentMarks, COUNT(*) AS cnt
FROM RowWithSameValue
GROUP BY StudentMarks
ORDER BY cnt DESC;
2. กรองเฉพาะค่าที่ซ้ำมากกว่า 1 ครั้ง (HAVING):
SELECT StudentMarks, COUNT(*) AS cnt
FROM RowWithSameValue
GROUP BY StudentMarks
HAVING COUNT(*) > 1;
3. นับค่าที่ไม่ซ้ำ (DISTINCT):
SELECT COUNT(DISTINCT StudentMarks) AS unique_scores
FROM RowWithSameValue;