Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Cách tính tổng điểm học sinh trùng tên trong MySQL có ORDER BY?

Tổng hợp điểm theo tên học sinh và sắp xếp trong MySQL

Sử dụng GROUP BY kết hợp SUM() để tính tổng điểm, thêm ORDER BY để sắp xếp kết quả.

Ví dụ: Tổng điểm toán theo tên, sắp xếp giảm dần

Tạo bảng:

mysql> CREATE TABLE countRowValueDemo (
    -> StudentId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> StudentName VARCHAR(20),
    -> StudentMathScore INT
    -> );

Chèn dữ liệu (có trùng tên David, John):

mysql> INSERT INTO countRowValueDemo(StudentName, StudentMathScore) VALUES
('Larry', 45), ('Mike', 56), ('John', 60), ('David', 40),
('David', 70), ('John', 80), ('David', 88);

Dữ liệu gốc:

+-----------+-------------+------------------+
| StudentId | StudentName | StudentMathScore |
+-----------+-------------+------------------+
| 1         | Larry       | 45               |
| 2         | Mike        | 56               |
| 3         | John        | 60               |
| 4         | David       | 40               |
| 5         | David       | 70               |
| 6         | John        | 80               |
| 7         | David       | 88               |
+-----------+-------------+------------------+

Trường hợp 1: Sắp xếp tổng điểm giảm dần (DESC)

mysql> SELECT StudentName, SUM(StudentMathScore) AS TOTAL_SCORE
FROM countRowValueDemo
GROUP BY StudentName
ORDER BY SUM(StudentMathScore) DESC;

Kết quả:

+-------------+-------------+
| StudentName | TOTAL_SCORE |
+-------------+-------------+
| David       | 198         |
| John        | 140         |
| Mike        | 56          |
| Larry       | 45          |
+-------------+-------------+

Trường hợp 2: Sắp xếp tổng điểm tăng dần (ASC)

mysql> SELECT StudentName, SUM(StudentMathScore) AS TOTAL_SCORE
FROM countRowValueDemo
GROUP BY StudentName
ORDER BY SUM(StudentMathScore) ASC;

Kết quả:

+-------------+-------------+
| StudentName | TOTAL_SCORE |
+-------------+-------------+
| Larry       | 45          |
| Mike        | 56          |
| John        | 140         |
| David       | 198         |
+-------------+-------------+

Tối ưu: Dùng alias trong ORDER BY

SELECT StudentName, SUM(StudentMathScore) AS TOTAL_SCORE
FROM countRowValueDemo
GROUP BY StudentName
ORDER BY TOTAL_SCORE DESC;

Mở rộng: Thêm COUNT, AVG

SELECT StudentName, 
       COUNT(*) AS ExamCount,
       SUM(StudentMathScore) AS TotalScore,
       AVG(StudentMathScore) AS AvgScore
FROM countRowValueDemo
GROUP BY StudentName
ORDER BY TotalScore DESC;

Lưu ý

  • GROUP BY gom nhóm trước, ORDER BY sắp xếp sau
  • Chỉ SELECT các cột trong GROUP BY hoặc aggregate function
  • MySQL ONLY_FULL_GROUP_BY mode bắt buộc tuân thủ quy tắc này