MySQL에서 GROUP BY와 ORDER BY로 같은 이름 학생 점수 합산하기
동일한 이름을 가진 여러 학생의 점수를 하나로 합산하려면 GROUP BY 절과 ORDER BY 절을 함께 사용하면 됩니다. GROUP BY는 같은 이름끼리 행을 그룹으로 묶어 점수를 집계하고, ORDER BY는 집계된 결과를 오름차순 또는 내림차순으로 정렬하는 역할을 합니다.
먼저 학생 이름과 수학 점수를 저장할 테이블을 생성해 보겠습니다.
mysql> create table countRowValueDemo
-> (
-> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> StudentName varchar(20),
-> StudentMathScore int
-> );
Query OK, 0 rows affected (0.71 sec)
이어서 INSERT 명령으로 테이블에 샘플 데이터를 입력합니다.
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('Larry',45);
Query OK, 1 row affected (0.19 sec)
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('Mike',56);
Query OK, 1 row affected (0.16 sec)
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('John',60);
Query OK, 1 row affected (0.15 sec)
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',40);
Query OK, 1 row affected (0.24 sec)
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',70);
Query OK, 1 row affected (0.12 sec)
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('John',80);
Query OK, 1 row affected (0.13 sec)
mysql> insert into countRowValueDemo(StudentName,StudentMathScore) values('David',88);
Query OK, 1 row affected (0.17 sec)SELECT 문으로 테이블에 저장된 전체 레코드를 확인해 보겠습니다.
mysql> select * from countRowValueDemo;
위 쿼리는 다음과 같은 결과를 출력합니다.
+-----------+-------------+------------------+
| StudentId | StudentName | StudentMathScore |
+-----------+-------------+------------------+
| 1 | Larry | 45 |
| 2 | Mike | 56 |
| 3 | John | 60 |
| 4 | David | 40 |
| 5 | David | 70 |
| 6 | John | 80 |
| 7 | David | 88 |
+-----------+-------------+------------------+
7 rows in set (0.00 sec)
결과를 보면 David는 3번, John은 2번 등록되어 있습니다. 이제 이름별로 점수를 합산해 보겠습니다.
사례 1: 내림차순 정렬(합계 기준)
같은 이름의 학생 점수를 합산하고, 그 결과를 내림차순으로 정렬하는 쿼리입니다.
mysql> 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 |
+-------------+-------------+
4 rows in set (0.00 sec)
사례 2: 오름차순 정렬(합계 기준)
반대로 합계 점수를 오름차순으로 정렬하려면 ORDER BY 절에서 DESC 키워드를 생략하면 됩니다.
mysql> 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 |
+-------------+-------------+
4 rows in set (0.00 sec)
이처럼 GROUP BY로 이름별 점수를 집계한 뒤 ORDER BY에 SUM() 함수를 적용하면, 합계 점수를 기준으로 원하는 방향으로 손쉽게 정렬할 수 있습니다.