Students and Examinations LeetCode Solution

Last updated on October 9th, 2024 at 10:04 pm

This Leetcode problem Students and Examinations LeetCode Solution is done in SQL.

List of all LeetCode Solution

Level of Question

Easy

Students and Examinations LeetCode Solution

Students and Examinations LeetCode Solution

Problem Statement

Column NameType
student_idint
student_namevarchar
Table: Students

student_id is the primary key (column with unique values) for this table.
Each row of this table contains the ID and the name of one student in the school.

Column NameType
student_namevarchar
Table: Subjects

subject_name is the primary key (column with unique values) for this table.
Each row of this table contains the name of one subject in the school.

Column NameType
student_idint
student_namevarchar
Table: Examinations

There is no primary key (column with unique values) for this table. It may contain duplicates.
Each student from the Students table takes every course from the Subjects table.
Each row of this table indicates that a student with ID student_id attended the exam of subject_name.

Write a solution to find the number of times each student attended each exam.

Return the result table ordered by student_id and subject_name.

The result format is in the following example.

Example 1:
Input:

student_id student_name
1Alice
2Bob
13John
6Alex
Students table:
subject_name
Math
Physics
Programming
Subjects table:
student_id subject_name
1Math
1Physics
1Programming
2Programming
1Physics
1Math
13Math
13Programming
13Physics
2Math
1Math
Examinations table:

Output:

student_id student_namesubject_name attended_exams
1AliceMath3
1AlicePhysics2
1AliceProgramming1
2BobMath1
2BobPhysics0
2BobProgramming1
6AlexMath0
6AlexPhysics0
6AlexProgramming0
13JohnMath1
13JohnPhysics1
13JohnProgramming1

Explanation:
The result table should contain all students and all subjects. Alice attended the Math exam 3 times, the Physics exam 2 times, and the Programming exam 1 time.
Bob attended the Math exam 1 time, the Programming exam 1 time, and did not attend the Physics exam.
Alex did not attend any exams.
John attended the Math exam 1 time, the Physics exam 1 time, and the Programming exam 1 time.

1. Students and Examinations LeetCode Solution MySQL

select 
  s.student_id, 
  s.student_name, 
  u.subject_name, 
  count(e.subject_name) as attended_exams 
from 
  Students as s 
  join Subjects as u 
  left join Examinations as e on s.student_id = e.student_id 
  and u.subject_name = e.subject_name 
group by 
  s.student_id, 
  u.subject_name 
order by 
  s.student_id, 
  u.subject_name;
Scroll to Top