There are 3 tables: Students table, Subjects table, and Examinations table.
Students table:
+------------+--------------+
| student_id | student_name |
+------------+--------------+
| 1 | Alice |
| 2 | Bob |
| 13 | John |
| 6 | Alex |
+------------+--------------+
Subjects table:
+--------------+
| subject_name |
+--------------+
| Math |
| Physics |
| Programming |
+--------------+
Examinations table:
+------------+--------------+
| student_id | subject_name |
+------------+--------------+
| 1 | Math |
| 1 | Physics |
| 1 | Programming |
| 2 | Programming |
| 1 | Physics |
| 1 | Math |
| 13 | Math |
| 13 | Programming |
| 13 | Physics |
| 2 | Math |
| 1 | Math |
+------------+--------------+
SQL code is as below:
SELECT s.student_id,s.student_name,b.subject_name,COUNT(e.subject_name) as attended_exams
FROM Students as s
INNER JOIN Subjects as b
LEFT JOIN Examinations as e
ON s.student_id=e.student_id AND b.subject_name=e.subject_name
GROUP BY s.student_id,b.subject_name;
The part I am confused with is the INNER JOIN
because Students table and Subjects table has no intersection or common columns. I guess my goal is to intuitively understand/imagine a table right before the LEFT JOIN
was executed. And also is it necessary to include the Subject table at all since we have all the subjects in the Examinations table already? Really appreciate the help!
This is actually a problem from LeetCode database. Link is below:
https://leetcode.com/problems/students-and-examinations/