Counting and averaging
Sometimes you do not want the rows themselves, but a summary of them. Aggregate functions turn many rows into a single value:
COUNT(*)— how many rowsSUM(col)— the totalAVG(col)— the averageMIN(col)/MAX(col)— the smallest / largest
SELECT COUNT(*) FROM student;
Give the result a clear heading with AS. Averages often have long decimals, so wrap them in ROUND(value, 2) to keep 2 decimal places:
SELECT COUNT(*) AS n, ROUND(AVG(score), 2) AS avg_score
FROM student;
You can combine several aggregates in one query.
Question. How many students in form 11A scored 85 or more? Show the answer under the heading n.
Answer. WHERE keeps the matching rows first; COUNT(*) then counts what is left:
SELECT COUNT(*) AS n FROM student
WHERE form = '11A' AND score >= 85;
n
3
Mei (88), Sara (95) and Lin (88) pass both tests. SUM works the same way: SELECT SUM(score) FROM student WHERE form = '11B' adds up only the 11B scores.
- "How many" is
COUNT; "total" isSUM.COUNT(score)counts the scores that are not empty (5 here);SUM(score)adds them up (407). - An aggregate cannot go in
WHERE.WHERE AVG(score) > 80fails withmisuse of aggregate function. Filter rows withWHEREand groups withHAVING(lesson 8). - Round an average with
ROUND(x, 2), or it may show a long decimal.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
In one query, show how many students there are as n, and their average score (to 2 decimal places) as avg_score.
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Show the lowest score as lowest, the highest as highest, and the total of all scores as total.
Click Run to see the output here.
Difficulty 2/5 · 140 coins + a small bonus on first completion today
Show the average score of the students in form 11A only, to 2 decimal places, under the heading avg_11a. The starter averages everyone: add a WHERE.
Click Run to see the output here.