Boss lesson · Unit 01
The sales report
COUNT, SUM, GROUP BY and HAVING, end to end
What you practise
COUNT,SUM,AVG,GROUP BY,HAVINGvsWHERE,COUNT(*)vsCOUNT(col), the order SQL clauses really run in, a subquery or CTE to finish the report
Try a question from this lesson
Pick one
The boss wants a report with one line per region and its total sales. How many lines will it have?
CREATE TABLE sales(region, rep, amount);
INSERT INTO sales VALUES
('north', 'Ana', 100),
('north', 'Bo', 50),
('south', 'Ana', 70),
('south', 'Cy', NULL),
('east', 'Bo', 30);Correct answer
3
Why
Five sales, but only three different regions: north, south and east. Turning many rows into one row per group is what this lesson builds, clause by clause.
The idea
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
GROUP BY: one row per group
GROUP BY region sorts the rows into piles, one pile per region, and each aggregate is computed per pile.
The output has one row per group. So next to the aggregates you may only select the columns you grouped by: a pile has one region, but many reps.
CREATE TABLE sales(region, rep, amount);
INSERT INTO sales VALUES
('north', 'Ana', 100),
('north', 'Bo', 50),
('south', 'Ana', 70),
('south', 'Cy', NULL),
('east', 'Bo', 30);
SELECT region, SUM(amount)
FROM sales
GROUP BY region
ORDER BY region;11 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 2× fill the blanks
- 2× order the lines
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.