Aggregates & GROUP BY
Databases summarise. Aggregate functions collapse many rows into one number: COUNT(*), SUM(col), AVG(col), MIN, MAX. On their own they summarise the whole table:
SELECT COUNT(*), AVG(price) FROM products;GROUP BY runs the aggregate per group instead: one row out per distinct value of the grouping column.
SELECT category, SUM(stock) FROM products GROUP BY category;
-- one (category, total) row per categoryWrite stock_by_category(con) returning a dict {category: total_stock} built from SELECT category, SUM(stock) ... GROUP BY category. Press Run.
Write stock_by_category(con) that returns a dict mapping each category to the SUM of its stock, using SELECT category, SUM(stock) FROM products GROUP BY category. Build the dict from the returned (category, total) rows.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.