The table below stores exam results.
| StudentID | Subject | Score |
|---|---|---|
| 1 | CS | 78 |
| 1 | Maths | 65 |
| 2 | CS | 55 |
| 2 | Maths | 70 |
| 3 | CS | 90 |
| 3 | Maths | 82 |
| 4 | CS | 48 |
| 5 | CS | 66 |
| 5 | Maths | 71 |
| 6 | CS | 72 |
Write an SQL query that outputs the StudentID and average Score of every student who has at least two results and an average score above 70. [4]
- SELECT StudentID, AVG(Score) FROM Result (accept AVERAGE(Score), the IB guide's wording; allow an alias, e.g. AS AvgScore)(1)
- GROUP BY StudentID(1)
- HAVING COUNT(*) >= 2 (accept COUNT(Score), COUNT(Subject), or > 1)(1)
- AND AVG(Score) > 70 in the HAVING clause (reject if either aggregate condition is placed in WHERE)(1)
- Answer: SELECT StudentID, AVG(Score) FROM Result GROUP BY StudentID HAVING COUNT(*) >= 2 AND AVG(Score) > 70; output (1, 71.5), (3, 86.0)
- Examiner tip: Conditions on aggregates go in HAVING; WHERE cannot use AVG or COUNT.