
Code
Totals by Island
The delivery log has one row per delivery. The quartermaster doesn't want 500 rows. She wants totals.
Aggregate functions
COUNT(*) counts rows. SUM(col), MIN(col) and MAX(col) do
what they say. On their own they squash the whole table into
one row:
conn.execute(
"SELECT COUNT(*), SUM(crates) FROM deliveries"
).fetchone() # (5, 31)
GROUP BY: one row per group
GROUP BY island makes a separate pile for each island. The
aggregates then run on each pile:
SELECT island, COUNT(*), SUM(crates) AS total
FROM deliveries
GROUP BY island
ORDER BY total DESC
AS total gives the column a nickname you can use in ORDER BY.
HAVING filters groups
WHERE filters rows before grouping. HAVING filters
groups after grouping, so it can use the totals:
... GROUP BY island HAVING SUM(crates) >= 10
Assignment
Let SQL do the counting. No Python loops.
island_totals(conn)returns a list of(island, deliveries, crates): how many deliveries each island got and the total crates. Islands A to Z.busy_islands(conn, min_crates)returns a list of(island, crates)for islands whose total is at leastmin_crates. Biggest total first; ties A to Z. UseHAVINGwith a?placeholder.
The program should print:
[('Amber Isle', 2, 12), ('Fog Reach', 1, 4), ('Gull Rock', 2, 15)]
[('Gull Rock', 15), ('Amber Isle', 12)]Let SQL do the counting. No Python loops.
island_totals(conn)returns a list of(island, deliveries, crates): how many deliveries each island got and the total crates. Islands A to Z.busy_islands(conn, min_crates)returns a list of(island, crates)for islands whose total is at leastmin_crates. Biggest total first; ties A to Z. UseHAVINGwith a?placeholder.
The program should print:
[('Amber Isle', 2, 12), ('Fog Reach', 1, 4), ('Gull Rock', 2, 15)]
[('Gull Rock', 15), ('Amber Isle', 12)]main.py Python sleeping
Press Run to try your code, then Check to test it.