문제
Write a solution to find the number of times each student attended each exam. Return the result table ordered by student_id and subject_name. The result format is in the following example.
- 각 student의 각 시험을 응시한 횟수 구하기
예시1
Input:
Students table:
+------------+--------------+
| student_id | student_name |
+------------+--------------+
| 1 | Alice |
| 2 | Bob |
| 13 | John |
| 6 | Alex |
+------------+--------------+
Subjects table:
+--------------+
| subject_name |
+--------------+
| Math |
| Physics |
| Programming |
+--------------+
Examinations table:
+------------+--------------+
| student_id | subject_name |
+------------+--------------+
| 1 | Math |
| 1 | Physics |
| 1 | Programming |
| 2 | Programming |
| 1 | Physics |
| 1 | Math |
| 13 | Math |
| 13 | Programming |
| 13 | Physics |
| 2 | Math |
| 1 | Math |
+------------+--------------+
Output:
+------------+--------------+--------------+----------------+
| student_id | student_name | subject_name | attended_exams |
+------------+--------------+--------------+----------------+
| 1 | Alice | Math | 3 |
| 1 | Alice | Physics | 2 |
| 1 | Alice | Programming | 1 |
| 2 | Bob | Math | 1 |
| 2 | Bob | Physics | 0 |
| 2 | Bob | Programming | 1 |
| 6 | Alex | Math | 0 |
| 6 | Alex | Physics | 0 |
| 6 | Alex | Programming | 0 |
| 13 | John | Math | 1 |
| 13 | John | Physics | 1 |
| 13 | John | Programming | 1 |
+------------+--------------+--------------+----------------+
풀이
1) CROSS JOIN을 통해 Students와 Subjects 테이블 JOIN
SELECT *
FROM Students s
CROSS JOIN Subjects sub
2) LEFT JOIN을 통해 1)의 테이블과 Examinations 테이블 JOIN
SELECT *
FROM Students s
CROSS JOIN Subjects sub
LEFT JOIN Examinations e ON s.student_id = e.student_id AND sub.subject_name = e.subject_name
3) GROUP BY student_id, student_name, subject_name을 통해 Examinations에서 가져온 subject_name을 COUNT
SELECT s.student_id, s.student_name, sub.subject_name, COUNT(e.subject_name) AS attended_exams
FROM Students s
CROSS JOIN Subjects sub
LEFT JOIN Examinations e ON s.student_id = e.student_id AND sub.subject_name = e.subject_name
GROUP BY s.student_id, s.student_name, sub.subject_name
ORDER BY s.student_id, sub.subject_name;
'SQL' 카테고리의 다른 글
[MySQL] 프로그래머스 - 물고기 종류 별 잡은 수 구하기 (0) | 2024.07.15 |
---|---|
[MySQL] 프로그래머스 - 노선별 평균 역 사이 거리 조회하기 (0) | 2024.07.07 |
[MySQL] 프로그래머스 - 월별 잡은 물고기 수 구하기 (0) | 2024.07.01 |
[MySQL] 프로그래머스 - 물고기 종류 별 대어 찾기 (0) | 2024.06.13 |
[MySQL] 프로그래머스 - 연도 별 평균 미세먼지 농도 조회하기 (0) | 2024.06.02 |