1280. Students and Examinations : Leetcode

오유찬·2025년 11월 25일

SQL

목록 보기
6/71
# student_id X subject_name
select st.student_id, st.student_name, su.subject_name
from Students st cross join Subjects su;
student_idstudent_namesubject_name
1AliceProgramming
1AlicePhysics
1AliceMath
2BobProgramming
2BobPhysics
2BobMath
13JohnProgramming
13JohnPhysics
13JohnMath
6AlexProgramming
6AlexPhysics
6AlexMath
# count attended_exams
select student_id, subject_name, count(subject_name)
from Examinations
group by student_id, subject_name;
student_idsubject_namecount(subject_name)
1Math3
1Physics2
1Programming1
2Programming1
13Math1
13Programming1
13Physics1
2Math1

answer

# combine above sqls
select st.student_id, st.student_name, su.subject_name, IFNULL(c.attended_exams, 0) as attended_exams
from Students st cross join Subjects su
    left join (select student_id, subject_name, count(subject_name) as attended_exams from 
    Examinations group by student_id, subject_name) as c
        on st.student_id = c.student_id AND su.subject_name = c.subject_name
order by student_id, subject_name;
student_idstudent_namesubject_nameattended_exams
1AliceMath3
1AlicePhysics2
1AliceProgramming1
2BobMath1
2BobPhysics0
2BobProgramming1
6AlexMath0
6AlexPhysics0
6AlexProgramming0
13JohnMath1
13JohnPhysics1
13JohnProgramming1
profile
열심히 하면 재밌다

0개의 댓글