MySQL-এ একই নামের একাধিক সারির স্কোর যোগফল (SUM) বের করে সর্ট করতে GROUP BY + SUM() + ORDER BY ব্যবহার করুন।
টেবিল ও ডেটা
CREATE TABLE count_row_value_demo (
student_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
student_name VARCHAR(20),
student_math_score INT
);
INSERT INTO count_row_value_demo (student_name, student_math_score) VALUES
('Larry', 45), ('Mike', 56), ('John', 60), ('David', 40),
('David', 70), ('John', 80), ('David', 88);
র Daten
+-----------+-------------+------------------+
| student_id| student_name| student_math_score|
+-----------+-------------+------------------+
| 1 | Larry | 45 |
| 2 | Mike | 56 |
| 3 | John | 60 |
| 4 | David | 40 |
| 5 | David | 70 |
| 6 | John | 80 |
| 7 | David | 88 |
+-----------+-------------+------------------+
গ্রুপ বাই + সম + অর্ডার বাই
কেস ১: অবরোহী ক্রম (DESC) — সর্বোচ্চ স্কোর আগে
SELECT student_name, SUM(student_math_score) AS total_score
FROM count_row_value_demo
GROUP BY student_name
ORDER BY SUM(student_math_score) DESC;
ফলাফল
+-------------+-------------+
| student_name| total_score |
+-------------+-------------+
| David | 198 |
| John | 140 |
| Mike | 56 |
| Larry | 45 |
+-------------+-------------+
কেস ২: আরোহী ক্রম (ASC) — ন্যূনতম স্কোর আগে
SELECT student_name, SUM(student_math_score) AS total_score
FROM count_row_value_demo
GROUP BY student_name
ORDER BY SUM(student_math_score) ASC;
ফলাফল
+-------------+-------------+
| student_name| total_score |
+-------------+-------------+
| Larry | 45 |
| Mike | 56 |
| John | 140 |
| David | 198 |
+-------------+-------------+
অ্যালIAS ব্যবহার করে ORDER BY (পরিষ্কার কোড)
SELECT student_name, SUM(student_math_score) AS total_score
FROM count_row_value_demo
GROUP BY student_name
ORDER BY total_score DESC;
HAVING ক্লজ (ফিল্টার গ্রুপ)
SELECT student_name, SUM(student_math_score) AS total_score
FROM count_row_value_demo
GROUP BY student_name
HAVING total_score > 100
ORDER BY total_score DESC;
ফলাফল: শুধু David (198) ও John (140)
COUNT, AVG, MIN, MAX একসাথে
SELECT
student_name,
COUNT(*) AS attempts,
SUM(student_math_score) AS total_score,
AVG(student_math_score) AS avg_score,
MIN(student_math_score) AS min_score,
MAX(student_math_score) AS max_score
FROM count_row_value_demo
GROUP BY student_name
ORDER BY total_score DESC;
দ্রষ্টব্য
GROUP BYকলামSELECT-এ থাকতে হয় (অথবাONLY_FULL_GROUP_BYঅফ থাকতে হয়)ORDER BY-এ অ্যালIAS বা এক্সপ্রেশন উভয় কাজ করে- বড় ডেটাসেটে ইনডেক্স:
INDEX idx_name_score (student_name, student_math_score)