코딩 테스트 연습/[프로그래머스][리트코드] MySQL

1280. Students and Examinations

duswjd_data 2025. 8. 28. 08:53

문제

https://leetcode.com/problems/students-and-examinations/description/


문제 설명

  • 모든 학생(Students)과 모든 과목(Subjects)의 조합에 대해, 각 학생이 해당 과목 시험을 몇 번 응시했는지 구하는 쿼리 작성
  • 결과
    • 응시 기록이 없는 경우(0)도 포함
    • student_id, subject_name 순으로 정렬

정답 코드

SELECT s.student_id,
       s.student_name,
       su.subject_name,
       COUNT(e.subject_name) AS attended_exams
FROM students s
    CROSS JOIN subjects su
    LEFT JOIN examinations e ON s.student_id = e.student_id
                                AND su.subject_name = e.subject_name
GROUP BY s.student_id, s.student_name, su.subject_name
ORDER BY s.student_id, su.subject_name

코드 설명

SELECT 
    s.student_id,              -- 학생의 고유 ID
    s.student_name,            -- 학생 이름
    su.subject_name,           -- 과목 이름
    COUNT(e.subject_name) AS attended_exams  -- 해당 학생이 해당 과목 시험을 본 횟수 (없으면 0)
FROM 
    students AS s              -- 학생 테이블
CROSS JOIN 
    subjects AS su             -- 모든 학생 × 모든 과목 조합을 만들기 위한 CROSS JOIN
LEFT JOIN 
    examinations AS e 
    ON s.student_id = e.student_id
    AND su.subject_name = e.subject_name  -- 학생 ID와 과목명이 모두 일치하는 시험 기록을 찾음
GROUP BY 
    s.student_id, 
    s.student_name, 
    su.subject_name           -- 각 학생-과목 조합별로 응시 횟수를 집계
ORDER BY 
    s.student_id, 
    su.subject_name           -- 결과를 학생 ID, 과목 이름 순으로 정렬