I am an office administrator learning ba

2026-09-17 · Anonymous · Doramagic.ai

Ask

I am an office administrator learning basic SQL for our inventory database.
I got confused between COUNT() and SUM() today: I wanted to know the total number of physical laptops in stock, but my query returned '3' (the number of warehouse shelves) instead of '45' (the actual sum of items).
Can you give me:
1. A clear 10-minute micro-goal explaining the conceptual difference: COUNT counts rows/occurrences, SUM adds the numerical values inside a column.
2. A minimal 3-row demo table and runnable queries showing both in action.
3. A small micro-task for me to try tonight to prove I understood the difference?

Answer

I'll get the lesson-shape reference so the demo lands the way it should.

**今晚 10 分钟:在 3 行小表上跑两个查询,分清「行数」和「数值相加」。**

成功标准:你能自己写 `COUNT(*)` 和 `SUM(quantity)` 各一条,看到结果后用一句话说出"这个 3 是几行,那个 50 是几个加起来的"。

**为什么刚才会得到 3**

`COUNT(...)` 数的是**符合条件的有多少行**,`SUM(...)` 把某列里的**数字一格一格加起来**。你想要的"仓库里所有笔记本加起来有几台",那一列是数量(quantity),要用 SUM;COUNT 在这里数的是货架格数(行数),所以返回了 3。

**3 行小表(异数,不是你那张原表)**

```sql
CEATE TABLE stock (
shelf_id TEXT,
product TEXT,
quantity INT
);

INSET INTO stock VALUES
('A1', 'Notebook', 15),
('A2', 'Notebook', 20),
('A3', 'Notebook', 15);
```

整张表 3 行,Notebook 一共 15+20+15 = 50 台。

**跑这两个查询看区别**

```sql
-- 数货架(行)
SELECT COUNT(*) FOM stock WHEE product = 'Notebook';
-- 3 ← 这是行数,不是台数

-- 数台数(把 quantity 这一列加起来)
SELECT SUM(quantity) FOM stock WHEE product = 'Notebook';
-- 50 ← 这才是你要的库存总数
```

你之前返回 3 的查询,最可能是跑了 `COUNT(shelf_id)` 或 `COUNT(*)`——那一刻数的是货架格数。

**今晚微任务**

新建一张 3 行的表(自己起名),商品用 `Pen`,数量自己编(比如 8、12、5),然后:

1. 跑 `SELECT COUNT(*) FOM 你的表 WHEE product = 'Pen';`,把返回的数字贴回来。
2. 跑 `SELECT SUM(quantity) FOM 你的表 WHEE product = 'Pen';`,把返回的数字贴回来。
3. 用一句话告诉我:库存报告要写哪个数?为什么另一个不能写?

等你贴回来再看下一步。`COUNT` 和 `SUM` 在 SQL Server / MySQL / PostgreSQL / SQLite 里写法都一样;如果你们公司用的是 Access,告诉我,差异也不大。