SQL: Display Full Name + Filter By Subject

abramlimpin picture abramlimpin · Jul 23, 2012 · Viewed 12.8k times · Source

Here are the following records inside my tables:

EnrollStudents

EnrollID     StudentID  SubjID
1            1          1
2            1          2
3            1          3
4            2          1
5            3          2

Students

StudentID     UserID     YearID     FirstName     LastName
1             1          1          John          Doe
2             3          1          Peter         Pan
3             7          1          Isaac         Newton

Subjects

SubjID     SubjCode     YearID
1          English      1
2          Math         1
3          Science      1

and the output should be...

StudentID     FullName
2             Peter Pan
3             Isaac Newton

I was able to come up with the following SQL statement (thanks to Ic.)

SELECT s.StudentID, s.FirstName + ' ' s.LastName AS FullName 
FROM Students AS s
LEFT OUTER JOIN EnrollStudents AS es ON s.StudentID = es.StudentID
GROUP BY s.StudentID, s.FirstName, s.LastName 
HAVING COUNT(DISTINCT(es.SubjID)) < (SELECT COUNT(*) FROM Subjects)

Is there a way that I can filter the query by subject? Let's say I select English, only Isaac Newton can enroll the subject.

Answer

D&#39;Arcy Rittich picture D'Arcy Rittich · Jul 23, 2012

You can use a simpler query to find students not enrolled in a subject, e.g.:

select StudentID,
    FirstName + ' ' + LastName as FullName
from Students
where StudentID not in (
    select es.StudentID
    from EnrollStudents es
    inner join Subjects s on es.SubjID = s.SubjID
    where s.SubjCode = 'English'
)

SQL Fiddle Example

You could also write it as a left join, like this:

select s.StudentID,
    s.FirstName + ' ' + s.LastName as FullName
from Students s
left outer join (
    select distinct es.StudentID
    from EnrollStudents es
    inner join Subjects s on es.SubjID = s.SubjID
    where s.SubjCode = 'English'
) ss on s.StudentID = ss.StudentID
where ss.StudentID is null