Chapter 3 · Lesson 3 of 7
COUNT and SUM Together
Return several aggregates in one query by combining COUNT and SUM, producing a compact one-row summary of a filtered set of sales.
Once you understand single aggregates, the next step is combining them. SQL lets you calculate several summaries in the same query.
For example:
SELECT COUNT(*) AS sale_count, SUM(amount) AS total_amount
FROM sales
WHERE region = 'West'This is very common in reporting and dashboards because one query can return multiple useful summary values at once.
Sample data
This lesson loads the sales table (8 rows) into DuckDB in your browser with one click, so you can run every example without uploading anything.
Setup SQL for sales
CREATE OR REPLACE TABLE sales (
id INTEGER,
salesperson VARCHAR,
region VARCHAR,
amount DECIMAL(10,2),
quantity INTEGER,
sale_date DATE
);
INSERT INTO sales VALUES
(1, 'Alice', 'West', 1200, 3, '2024-01-05'),
(2, 'Bob', 'East', 850, 2, '2024-01-08'),
(3, 'Alice', 'West', 640, 1, '2024-01-11'),
(4, 'Diana', 'South', 430, 5, '2024-01-12'),
(5, 'Eve', 'West', 1500, 4, '2024-02-01'),
(6, 'Frank', 'East', 920, 2, '2024-02-03'),
(7, 'Grace', 'North', 760, 2, '2024-02-07'),
(8, 'Bob', 'East', 1100, 3, '2024-02-10');Practice challenge
For the West region, return the number of sales as sale_count and the total amount as total_amount.
Hint: Use COUNT(*) AS sale_count and SUM(amount) AS total_amount with WHERE region = 'West'.
Run your query in the editor and the lesson checks the result automatically.
Lessons in Simple Aggregates
Summarize a whole table into single values with COUNT, SUM, MIN, MAX, and AVG.