JOIN with GROUP BY
Many exam problems join tables and then evaluate per group.
Rules
- Join first, then group
- LEFT JOIN keeps rows without a partner
- COUNT(column) skips NULL
Your turn
Three problems on this topic. You can run the query first.
- 1 · JOIN & GROUP BY
- 2
- 3
For each student give the name and the average grade (only students with grades).
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | Greta | Chemistry | 4 | Berlin |
| 2 | Clara | Chemistry | 3 | Wien |
| 3 | Nora | Computing | 3 | Bern |
| 4 | Jonas | Computing | 4 | Zürich |
| 5 | Eva | Law | 8 | Wien |
| 6 | Max | Chemistry | 2 | Basel |
| 7 | Felix | Chemistry | 7 | Zürich |
grades
| student_id | course_id | grade |
|---|---|---|
| 1 | 1 | 2.3 |
| 5 | 3 | 2 |
| 4 | 1 | 2 |
| 2 | 1 | 2.3 |
| 3 | 4 | 4 |
| 2 | 4 | 3.3 |
| 5 | 1 | 3 |
| 6 | 1 | 2 |
| 1 | 3 | 2 |
| 5 | 2 | 1 |
| 4 | 2 | 3 |
| 4 | 4 | 1 |
| 3 | 2 | 2 |
+ − More tables: courses
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Calculus | 6 | Meier |
| 2 | Databases | 6 | Keller |
| 3 | Statistics | 6 | Huber |
| 4 | Marketing | 6 | Meier |
SQL
Any equivalent query counts. It is also checked on data you can’t see.
Worked example
For each student give the name and the number of entries; students without grades with 0.
students
| id | name | major | semester | city |
|---|---|---|---|---|
| 1 | Anna | Business | 5 | Wien |
| 2 | Lena | Law | 1 | Zürich |
| 3 | David | Computing | 4 | Basel |
| 4 | Jonas | Law | 4 | Basel |
| 5 | Clara | Computing | 4 | Bern |
| 6 | Max | Law | 8 | Zürich |
| 7 | Hannah | Chemistry | 5 | Berlin |
grades
| student_id | course_id | grade |
|---|---|---|
| 7 | 4 | 2.3 |
| 5 | 4 | 3.3 |
| 2 | 4 | 1 |
| 5 | 2 | 1 |
| 3 | 3 | 3.7 |
| 4 | 4 | 1.3 |
| 7 | 3 | 1.7 |
| 6 | 4 | 3.7 |
| 4 | 2 | 3.7 |
| 5 | 1 | 3.3 |
| 6 | 2 | 3.3 |
| 4 | 1 | 3.3 |
+ − More tables: courses
courses
| id | title | credits | lecturer |
|---|---|---|---|
| 1 | Marketing | 4 | Huber |
| 2 | Calculus | 5 | Weber |
| 3 | Law | 4 | Weber |
| 4 | Statistics | 3 | Meier |
Worked solution
SELECT s.name, COUNT(n.grade) FROM students s LEFT JOIN grades n ON s.id = n.student_id GROUP BY s.name
Result on the sample data:
name | count
Anna | 0
Lena | 1
David | 1
Jonas | 3
Clara | 3
Max | 2
Hannah | 2
Typical mistake: LEFT JOIN keeps rows without a partner; COUNT(column) skips NULL.
Common questions
When do I need LEFT JOIN?
When rows without a matching partner should also appear in the result.
