Counting and averaging · 计数与求平均
Summarising with aggregate functions
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
用聚合函数做汇总
有时你要的不是一行行的数据,而是它们的汇总。聚合函数把许多行变成一个值:
COUNT(*)—— 有多少行SUM(col)—— 总和AVG(col)—— 平均值MIN(col)/MAX(col)—— 最小值 / 最大值
SELECT COUNT(*) FROM student;
Naming and rounding the result
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:
You can combine several aggregates in one query.
给结果命名并四舍五入
用 AS 给结果一个清晰的标题。平均值常常有很长的小数,所以用 ROUND(value, 2) 保留两位小数:
SELECT COUNT(*) AS n, ROUND(AVG(score), 2) AS avg_score
FROM student;
你可以在一条查询里组合多个聚合函数。
Common mistakes
COUNT(*)counts rows;AVG(col)averages a column.- Round an average with
ROUND(x, 2).
常见错误
COUNT(*)统计行数;AVG(col)求列的平均值。- 用
ROUND(x, 2)对平均值取整。
In one query, show how many students there are as n, and their average score (to 2 decimal places) as avg_score. · 用一条查询,显示学生人数(命名为 n),以及他们的平均分(保留两位小数,命名为 avg_score)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Show the lowest score as lowest, the highest as highest, and the total of all scores as total. · 显示最低分(命名为 lowest)、最高分(命名为 highest)和所有分数的总和(命名为 total)。
Click Run to see the output here. · 点击“运行”查看此处输出。