CleverSphere

SQL: GROUP BY

GROUP BY forms groups of equal values. Aggregates are then worked out per group.

Rules

  • Every non-aggregated column goes in GROUP BY
  • One result row per group

Your turn

Three problems on this topic. You can run the query first.

  1. 1 · GROUP BY
  2. 2
  3. 3

How many students are there per city? Give the city and the count.

students

idnamemajorsemestercity
1GretaChemistry7Basel
2MaxLaw2Bern
3BenBusiness6Zürich
4EvaBusiness7Wien
5JonasBusiness7Wien
6AnnaChemistry7Berlin
7HannahChemistry2Zürich
+ More tables: courses, grades

courses

idtitlecreditslecturer
1Statistics5Meier
2Marketing6Huber
3Databases4Keller
4Calculus3Meier

grades

student_idcourse_idgrade
733.7
233.7
223.3
112.7
141.3
741.7
521.7
441.3
131.7
541
243.7
433.3
331.3

SQL

Any equivalent query counts. It is also checked on data you can’t see.

Worked example

What is the average semester per major? Give the major and the average.

students

idnamemajorsemestercity
1LenaBusiness1Wien
2BenComputing2Berlin
3HannahComputing1Bern
4FelixLaw8Wien
5ClaraChemistry8Berlin
6DavidBusiness2Wien
7EvaComputing2Bern
+ More tables: courses, grades

courses

idtitlecreditslecturer
1Law3Huber
2Calculus5Huber
3Statistics6Weber
4Marketing3Keller

grades

student_idcourse_idgrade
712
543.3
632
323
143.3
621.7
312.3
112
333.7
521.7
211.7

Worked solution

SELECT major, AVG(semester) FROM students GROUP BY major

Result on the sample data:

major | avg

Business | 1.5

Computing | 1.666667

Law | 8

Chemistry | 8

Typical mistake: GROUP BY makes one row per group.

Common questions

Why do I get a “not in GROUP BY” error?

Because a non-aggregated column would be ambiguous.

Related

More topics