I have a database of assessment outcomes, with fields identifying the pupil, grade, the year and term. The query below finds me pupils who have an assessment for a specific subject at some start and end point:
SELECT
a1.PupilId
FROM assessment as a1
JOIN assessment as a2
USING (PupilId)
WHERE a1.GradeID in('1A','1B','1C')
AND a2.GradeID in('5A','5B','5C')
AND a1.NCYear = '1'
AND a1.Term = '6'
AND a2.NCYear = '2'
AND a2.Term = '6'
AND a1.Subject = '31'
AND a2.Subject = '31'
AND a1.Type = 'assessment'
AND a2.Type = 'assessment'
This works fine, but now I want to find pupils who have the starting grade (i.e. NCYear=’1′ and Term=’6′) but don’t have an entry for the end grade. I’ve played around with NOT EXISTS, but can’t get it to work.
To clarify, here’s the assessment table:
id | Subject | PupilId | NCYear | Term | GradeID | Type
--------------------------------------------------------
1 | 31 | 1 | 1 | 6 | 1A | assessment
2 | 31 | 1 | 2 | 6 | 5A | assessment
3 | 31 | 2 | 1 | 6 | 1A | assessment
The SQL query above should return PupilID 1. I need the query which will return PupilID 2, the start assessment is there but no end one.
Any suggestions?
You need to use an OUTER JOIN: