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.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
한 개의 쿼리로 n에 해당하는 학생 수와 그들의 평균 점수(소수점 2자리)를 avg_score로 표시하십시오.
출력을 보려면 '실행'을 클릭하세요.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
최저점을 lowest, 최상점을 highest, 모든 점수의 합계를 total로 표시하십시오.
출력을 보려면 '실행'을 클릭하세요.
난이도 2/5 · 140코인 + 오늘 첫 완료 시 작은 보너스 추가
형식 11A의 학생 평균 점수를 2 소수점 자리까지, avg_11a 제목 아래에 표시하시오. 스타터는 모든 사람을 평균화하므로, WHERE을 추가하십시오.
출력을 보려면 '실행'을 클릭하세요.