[LeetCode] SQL 50 / MySQL / 1280. Students and Examinations

2024. 1. 6. 17:58Coding/LeetCode-SQL

문제 링크

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

 

Students and Examinations - LeetCode

Can you solve this real interview question? Students and Examinations - Table: Students +---------------+---------+ | Column Name | Type | +---------------+---------+ | student_id | int | | student_name | varchar | +---------------+---------+ student_id is

leetcode.com

 

문제

 

코드

# Write your MySQL query statement below
SELECT A.student_id, A.student_name, B.subject_name, count(C.subject_name) AS attended_exams
FROM Students As A
INNER JOIN Subjects As B
LEFT JOIN Examinations AS C
    ON A.student_id = C.student_id
    AND B.subject_name = C.subject_name
GROUP BY A.student_id, B.subject_name
ORDER BY A.student_id, B.subject_name;

 

1. 칼럼이 세 개 주어져서 삼중 조인을 실시해야한다.

Students 테이블에선 student_id 칼럼이 기본 키, Examinations에선 기본키가 없으므로 LEFT JOIN을 실시하고 마찬가지로 Subjects 테이블에서도 subject_name 칼럼이 기본 키, Examinations 에선 기본키가 없으므로 LEFT JOIN을 실시한다.

Students와 Subjects 테이블은 기본키가 있으므로 INNER JOIN을 해준다.

2. 두 번째 줄 조건에 따라 ORDER BY 절을 위와 같이 구현한다.

3. 'each student attended each exam' 이라는 조건 때문에 GROUP BY 절에 student_id와 subject_name을 넣어준다. 

4. 'find the number of times ~' 라고 했으므로 count() 함수를 subject_name 에 적용한다.