SQL Interview Questions – Students and Examinations

Spread the love

Problem Description –

Write an SQL query to find the number of times each student attended each exam.

Return the result table ordered by student_id and subject_name.

The query result format is in the following example.

Difficulty Level – Easy

Problem Link – Students and Examinations

Solution –

with student_subject as (
SELECT
    student_id,
    student_name,
    subject_name
FROM Students, Subjects
ORDER BY 1
), student_exam as (
SELECT
    student_id,
    subject_name,
    COUNT(*) as attended_exams
FROM Examinations
GROUP BY 1, 2 
ORDER BY 1
) 
SELECT
    ss.student_id,
    ss.student_name,
    ss.subject_name,
    IFNULL(se.attended_exams,0) as attended_exams
FROM student_subject as ss LEFT JOIN student_exam as se
ON ss.student_id = se.student_id
AND ss.subject_name = se.subject_name
ORDER BY 1, 3

To solve this problem first we have to cross join of students and subjects table.

SELECT
    student_id,
    student_name,
    subject_name
FROM Students, Subjects

Next we need to find the number of times each student attended each exam.

SELECT
    student_id,
    subject_name,
    COUNT(*) as attended_exams
FROM Examinations
GROUP BY 1, 2 
ORDER BY 1

Now, all we need to do is join these two tables using a left join and replace null values in attended exams with zeros as Alex did not appear for any exams.

Rating: 1 out of 5.

2 thoughts

  1. Hi Bhola,

    Thanks for sharing such a good content.
    could you please let me know which database you are using for these queries, i am using sql server, facing few syntactical issues.

    Regards
    Sourav

Leave a Reply