🔗 Problem Link

 

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


❔Thinking

  • 학생 개개인의 과목별 시험 본 횟수를 알아내야 한다.
  • 시험을 보지 않은 과목은 0번 본 것으로 생각해야 한다.

💻Solution

SELECT St.student_id, St.student_name, Su.subject_name, COUNT(Ex.student_id) AS attended_exams
FROM Students AS St
CROSS JOIN Subjects AS Su
LEFT JOIN Examinations AS Ex ON St.student_id = Ex.student_id AND Su.subject_name = Ex.subject_name
GROUP BY St.student_id, Su.subject_name
ORDER BY St.student_id, Su.subject_name

🗝️keypoint

  1. CROSS JOIN은 곱집합으로, 모든 경우의 수를 구하는 것과 같은 결과이다.
  2. COUNT 함수는 정확한 GROUP BY와 함께 쓰여야 한다.

+ Recent posts