TIL-sparta

LeetCode) 1280. Students and Examinations 풀이 (MySQL)

Megadr0ne 2024. 7. 12. 01:11

 

학습 키워드: MySQL

 

1280 - Students and Examinations

1) 문제 설명 요약 (원문은 링크 참고):

 

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

 

 요약: Students 테이블, Subjects 테이블, 그리고 Examinations 테이블을 이용해서 모든 학생들의 각 과목 시험 출석 횟수데이터를 가져오면 되는 문제다.

 

 fields: student_id, student_name, subject_name, attended_exams

 

 

 

 

 

2) 풀이 과정:

 처음 풀땐 그냥 세 테이블을 합쳐서 결과를 얻으려 했는데, 지난번처럼 attend 하지 않은 과목이 출력되지 않는 문제가 있었다. 그래서 with 절로 모든 combination을 미리 찾아두고 이를 Examinations 테이블과 join하는 방식으로 해서 해결했다.

 

 

3) 풀이 (정답):

WITH all_combinations AS (
    SELECT st.student_id AS student_id,
        st.student_name AS student_name,
        sb.subject_name AS subject_name
    FROM Students st
    CROSS JOIN Subjects sb
)

SELECT ac.student_id,
    ac.student_name,
    ac.subject_name,
    COALESCE(COUNT(ex.student_id), 0) AS attended_exams
FROM all_combinations ac
LEFT JOIN Examinations ex
    ON ac.student_id = ex.student_id
    AND ac.subject_name = ex.subject_name
GROUP BY 1, 3
ORDER BY 1, 3

 

728x90