SUM + GROUP BY + ORDER BY สำหรับข้อมูลซ้ำ
จัดกลุ่มตามชื่อ แล้วรวมคะแนน (SUM) และเรียงลำดับ (ORDER BY)
สร้างตาราง
CREATE TABLE countRowValueDemo (
StudentId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentName VARCHAR(20),
StudentMathScore INT
);
ข้อมูลทดสอบ (มีชื่อซ้ำ)
INSERT INTO countRowValueDemo(StudentName, StudentMathScore) VALUES
('Larry', 45), ('Mike', 56), ('John', 60),
('David', 40), ('David', 70), ('John', 80), ('David', 88);
Case 1: เรียง Descending (คะแนนมาก → น้อย)
SELECT StudentName, SUM(StudentMathScore) AS TOTAL_SCORE FROM countRowValueDemo GROUP BY StudentName ORDER BY SUM(StudentMathScore) DESC;
+-------------+-------------+ | StudentName | TOTAL_SCORE | +-------------+-------------+ | David | 198 | | John | 140 | | Mike | 56 | | Larry | 45 | +-------------+-------------+
Case 2: เรียง Ascending (คะแนนน้อย → มาก)
SELECT StudentName, SUM(StudentMathScore) AS TOTAL_SCORE FROM countRowValueDemo GROUP BY StudentName ORDER BY SUM(StudentMathScore);
+-------------+-------------+ | StudentName | TOTAL_SCORE | +-------------+-------------+ | Larry | 45 | | Mike | 56 | | John | 140 | | David | 198 | +-------------+-------------+
Best Practice
- ใช้ Alias ใน ORDER BY:
ORDER BY TOTAL_SCORE DESC(MySQL รองรับ) - เพิ่ม
COUNT(*) AS ExamCountเพื่อดูจำนวนครั้งที่สอบ - Index บน StudentName จะเร่ง GROUP BY