A3.3.4 · Database programming
A3.3.4 · 数据库编程
Calculations with aggregate functions
用聚合函数做计算
A bike shop owner does not want to read eight hundred repair records. She wants four numbers: how many, how much, the cheapest, the dearest. That is the entire job of an aggregate function.
一家自行车店的店主不想读八百条维修记录。她想要四个数字:有多少、花了多少、最便宜的、最贵的。这就是聚合函数的全部工作。
Explainer
讲解
Every query so far returned rows. SELECT with a JOIN returns rows, WHERE returns fewer rows, ORDER BY returns the same rows rearranged. An aggregate function does something different in kind: it reads many rows and returns a single calculated value.
到目前为止的每个查询返回的都是行。带 JOIN 的 SELECT 返回行,WHERE 返回更少的行,ORDER BY 返回重新排列的同样的行。聚合函数做的是性质不同的事:它读取许多行,返回一个计算出的值。
Every SELECT so far has handed back rows, one row per matching record. An aggregate function breaks that pattern: it reaches across as many records as match, and hands back a single number summarizing all of them. The five on the syllabus are COUNT, SUM, AVERAGE, MIN and MAX.
到目前为止的每条 SELECT 都交回行,每条匹配的记录一行。聚合函数打破了这种模式:它跨越所有匹配的记录,交回一个汇总所有记录的数字。考纲上的五个是 COUNT、SUM、AVERAGE、MIN 和 MAX。
Four of the five need a numeric field, since you cannot total or average text. COUNT is the exception: it counts records, so it works on any field at all.
五个中有四个需要数值字段,因为你不能对文本求和或求平均。COUNT 是例外:它数的是记录,所以对任何字段都可用。
The syllabus says AVERAGE, the database says AVG. The assessment statement names the function AVERAGE, but almost every real system implements it as AVG(...), and that is the form real SQL implementations use. Write AVG in the query and use the word "average" when describing what it does. Exact syntax varies between database systems, which the syllabus states outright, so a marker is reading for the right function, not one specific spelling.
考纲说 AVERAGE,数据库说 AVG。评估陈述把这个函数叫 AVERAGE,但几乎所有真实系统都把它实现为 AVG(...),这也是真实 SQL 实现使用的形式。在查询中写 AVG,描述它的作用时使用"average(平均值)"这个词。不同数据库系统的确切语法各不相同,考纲也明确说了这一点,所以阅卷员看的是你有没有用对函数,而不是某一种具体拼写。
The five functions
五个函数
| Function | 函数 | What it returns | 返回什么 | Example | 示例 |
|---|---|---|---|---|---|
| COUNT | How many matching rows there are. This is the only one of the five that makes sense on a text field, since it never looks at the values themselves, just tallies rows. | 有多少匹配的行。这是五个中唯一对文本字段也有意义的,因为它从不查看值本身,只是数行数。 | SELECT COUNT(RepairID) FROM Repair; | ||
| SUM | Every matching value in that column, added together into one running total. | 该列中所有匹配的值加在一起,得到一个累计总和。 | SELECT SUM(PartsCost) FROM Repair; | ||
| AVG | The mean of every matching value. The syllabus calls this AVERAGE, but the function itself is written AVG. | 所有匹配值的平均数。考纲把它称为 AVERAGE,但函数本身写作 AVG。 | SELECT AVG(PartsCost) FROM Repair; | ||
| MIN | Whichever matching value is lowest, found by scanning them all and keeping the smallest. | 所有匹配的值中最小的那个,通过扫描全部并保留最小的得到。 | SELECT MIN(PartsCost) FROM Repair; | ||
| MAX | The mirror of MIN, whichever matching value comes out highest. | MIN 的镜像,所有匹配的值中最大的那个。 | SELECT MAX(PartsCost) FROM Repair; |
Explainer
讲解
How GROUP BY changes the answer
GROUP BY 如何改变答案
Used alone, an aggregate function gives one number for the whole table. That is often not the number anyone wants.
单独使用时,聚合函数给出的是整张表的一个数字。这往往不是任何人想要的数字。
Without GROUP BY, the entire table is treated as one pile, and the function returns exactly one row: one total, one average, one maximum.
没有 GROUP BY 时,整张表被当作一堆,函数恰好返回一行:一个总和、一个平均值、一个最大值。
With GROUP BY, the rows are first sorted into piles by the value of some column, and the function then runs separately on each pile. Five bike types means five answers, not one.
有 GROUP BY 时,行先按某一列的值分成几堆,然后函数在每一堆上分别运行。五种自行车类型就有五个答案,而不是一个。
This is where the reporting value comes from. "Total parts cost: 1000.00" tells the owner almost nothing. "Electric bikes: 570.00 across only 2 repairs" tells her what to stock and what to charge. Click through and watch the collapse happen.
报表的价值就来自这里。"零件总成本:1000.00"几乎没告诉店主任何东西。"电动自行车:570.00,只有 2 次维修"则告诉她该备什么货、该收多少钱。点击查看这种折叠是如何发生的。
Worked example
例题讲解
REPAIR: building the shop report one function at a time
REPAIR:一次一个函数,构建商店报表
The same eight repair records, answering a different business question at every step.
同样的八条维修记录,每一步回答一个不同的业务问题。
Try it yourself
动手试试
Run your own queries
运行你自己的查询
The same two tables, live. Type a statement and run it. Reading a worked example proves nothing until you have written one and watched it fail, so the errors here are written to tell you what is actually wrong rather than just refusing. Everything A3.3 teaches works, not only this statement's own commands, so the INSERT, UPDATE and DELETE from A3.3.3 run here too and really do change the tables until you reset them.
同样的两张表,可在线运行。输入一条语句并运行它。读一个例题,在你亲手写过、并看着它失败之前,什么也证明不了,所以这里的错误提示被写成告诉你究竟哪里不对,而不是简单地拒绝。A3.3 教的一切都能运行,不只是这条陈述自己的命令,所以 A3.3.3 的 INSERT、UPDATE 和 DELETE 在这里也能运行,并且在你重置之前,确实会改变这些表。
8 rows
3 rows
Things worth trying. Put an aggregate inside WHERE and see what it says. Remove GROUP BY from a query that selects a plain column next to a SUM. Ask for AVERAGE(PartsCost) using the syllabus spelling instead of AVG. Each of those is a real exam error, and it is much easier to remember one you have triggered yourself.
值得尝试的事。把聚合函数放进 WHERE,看看它说什么。在一个把普通列和 SUM 一起选出来的查询中去掉 GROUP BY。用考纲的拼写 AVERAGE(PartsCost) 代替 AVG 来查询。这些都是真实的考试错误,亲手触发过的更容易记住。
Check your understanding
检查你的理解
Why does SELECT BikeType, MechanicID, SUM(PartsCost) FROM Repair GROUP BY BikeType; fail?
为什么 SELECT BikeType, MechanicID, SUM(PartsCost) FROM Repair GROUP BY BikeType; 会失败?
Common mistake
常见错误
A3.3.4A3.3.4 的这一常见模式RecurringConstructed queries frequently select a column that is neither wrapped in an aggregate function nor listed in the GROUP BY. The query looks reasonable and reads well in English, but it asks the database for a value that does not exist: one name, one date or one ID for a group that contains many different ones.
反复出现构建的查询经常选出一个既没有被聚合函数包起来、也没有列在 GROUP BY 中的列。这样的查询看起来合理,用英语读起来也通顺,但它向数据库要的是一个不存在的值:为一个包含许多不同值的组,给出一个名字、一个日期或一个 ID。
What a weak answer looks like: SELECT BikeType, MechanicID, SUM(PartsCost) FROM Repair GROUP BY BikeType; The Mountain row would have to show one MechanicID, but three different mechanics worked on mountain bikes. There is no correct value to print.
较弱的答案是这样的:SELECT BikeType, MechanicID, SUM(PartsCost) FROM Repair GROUP BY BikeType; Mountain 那一行得显示一个 MechanicID,但有三位不同的机械师修过山地车。没有正确的值可以显示。
What it should say: either drop the loose column, SELECT BikeType, SUM(PartsCost) ... GROUP BY BikeType;, or group by it as well, GROUP BY BikeType, MechanicID;, which gives one row per bike type per mechanic. Check every column in the SELECT list against that rule before writing the query down.
应该这样写:要么去掉多余的那一列,SELECT BikeType, SUM(PartsCost) ... GROUP BY BikeType;,要么也按它分组,GROUP BY BikeType, MechanicID;,这样每种自行车类型、每位机械师各一行。在写下查询之前,用这条规则检查 SELECT 列表中的每一列。
Revision questions
复习题
Past-paper style. Write an answer, then reveal the marking points and mark yourself.
仿真题风格。先写出你的答案,再显示评分要点并给自己打分。
[2]Construct a query that returns the total parts cost of every repair in the REPAIR table.
[2]构建一条查询,返回 REPAIR 表中所有维修的零件总成本。
Marking points
评分要点
- SELECT SUM(PartsCost) FROM REPAIR.
- SUM adds the numeric column across every row, returning one total.
- SELECT SUM(PartsCost) FROM REPAIR。
- SUM 把该数值列在所有行上相加,返回一个总和。
[4]Construct a query that shows, for each bike type, the number of repairs and the average parts cost.
[4]构建一条查询,对每种自行车类型显示维修次数和平均零件成本。
Marking points
评分要点
- SELECT BikeType, COUNT(*), AVG(PartsCost) FROM REPAIR.
- GROUP BY BikeType so the aggregates are computed once per bike type.
- COUNT(*) gives the number of repairs; AVG(PartsCost) gives the mean parts cost for that type.
- Every non-aggregated selected column (BikeType) must appear in GROUP BY.
- SELECT BikeType, COUNT(*), AVG(PartsCost) FROM REPAIR。
- GROUP BY BikeType,使聚合按每种车型各算一次。
- COUNT(*) 给出维修次数;AVG(PartsCost) 给出该车型的平均零件成本。
- 每个未聚合的被选列(BikeType)都必须出现在 GROUP BY 中。
[5]Construct a query joining REPAIR and MECHANIC that lists each mechanic's name and their highest single parts cost, showing only mechanics who have completed more than two repairs.
[5]构建一条连接 REPAIR 和 MECHANIC 的查询,列出每位机械师的姓名以及他们单次最高的零件成本,只显示完成了超过两次维修的机械师。
Marking points
评分要点
- Join REPAIR and MECHANIC on the mechanic foreign key.
- SELECT Mechanic.Name, MAX(REPAIR.PartsCost).
- GROUP BY the mechanic (name or ID).
- HAVING COUNT(*) > 2 keeps only mechanics with more than two repairs, filtering groups after aggregation.
- 按机械师外键连接 REPAIR 和 MECHANIC。
- SELECT Mechanic.Name, MAX(REPAIR.PartsCost)。
- 按机械师(姓名或编号)GROUP BY。
- HAVING COUNT(*) > 2 只保留维修次数超过两次的机械师,在聚合之后筛选组。
Flashcards
闪卡
Active recall for this statement's key terms.
针对本条陈述关键术语的主动回忆。
Keep this statement's practice with you
把本条陈述的练习带在身边
Free account: unlock every revision question and flashcard for A3.3.4, and every other IB CS 2027 statement.
免费账号:解锁 A3.3.4 以及其他所有 IB CS 2027 陈述的全部复习题和闪卡。