SQL/리트코드 문제풀이

[LeetCode] 1280 Students and Examinations

너지살 2024. 5. 18. 16:47

 

 

 

문제 출저

https://leetcode.com/problems/students-and-examinations/description/?envType=study-plan-v2&envId=top-sql-50

 

 

 

문제 풀이

각 학생이 시험을 몇 번 참석했는지 구해야 합니다. 

 

cross join으로 Students와 Subject를 연결시켜 각 학생이 시험을 참여한 모든 경우의 수를 구합니다.

left join으로 Examinations와 연결합니다.

group by로 student_id, subject_name 그룹화하여 count를 통해 갯수를 셉니다.

order by로 student_id, subject_name 순서로 정렬시킵니다. 

 

 

SQL

-- select * 
-- from Students 
-- cross join Subjects

/*

이 문제의 핵심은 student와 subject를 모두 출력해야 하는 것 이다.
cross join을 사용하여 student, subject를 모든 조합을 만든다.
이 조인된 테이블에 left join으로 시험 정보를 Examination을 연결한다. 
select의 count(e.studnet_id)를 통해 시험 본 횟수를 집계한다. 

*/


select 
    s.student_id,
    s.student_name, 
    sub.subject_name,
    count(e.student_id)
    as attended_exams
from
    Students as s 
cross join
    Subjects as sub 
left join
    Examinations as e 
on
     s.student_id = e.student_id and sub.subject_name = e.subject_name
group by
    student_id, subject_name
order by
    student_id, subject_name