Module 3 · Sorting and summarising

Practice: combine filters and summaries

By the end you will be able to combine filters and summaries without confusing what each figure counts.

About 25 min

0 of 52 lessons

Before you start, you need

Filter groups with HAVING

The problem

You will prepare a summary of stock per category and another of orders per status. In both cases you will have to decide which rows participate, how to group them and what to calculate.

A product with 30 units is still a product. COUNT(*) counts products and SUM(stock) adds up units. Use clear names so readers know what each figure represents.

Work in this order: filter the rows with WHERE, form the groups with GROUP BY and calculate their measures. If the task requires a condition on the summary, apply it with HAVING.

Before checking, look for one group that should pass and one that should not. Check the exact limit too. A query that runs without errors may still be counting something other than what was asked.

How to think about it

Which categories reach a threshold of two products if you remove the out-of-stock ones first?

  • First remove the out-of-stock products. Group the remaining ones by category.
  • Count products to decide whether the group passes, and add up stock to measure units. They are two different measures.
  • In the orders challenge, keep the same strategy, but decide what a row means and which amount you should add up.

Guided practice

Getting things wrong is part of learning: you can run your query as many times as you like and nothing is lost. If you get stuck, open a hint (each one reveals a bit more) and save the solution for last.

Guided practice

Summarise stock by category

Not started

Add up the positive stock per category. Return category and the sum with the alias total_stock; keep the categories with at least two products in stock.

Expected result: 2 rows with the columns category, total_stock, in that order. Row order does not matter.

View tables and data

Open this panel to see the full data.

Challenge

Solve this variation. Spot the part that has changed before you look for help.

Practice

Summarise orders without joins

Not started

Show status, COUNT(*) as orders and ROUND(SUM(total), 2) as amount. Keep only the statuses with two or more orders.

Expected result: 3 rows with the columns status, orders, amount, in that order. Row order does not matter.

View tables and data

Open this panel to see the full data.

Key takeaways

  • State the unit of each figure.
  • Filter rows before summarising when the question requires it.
  • Filter groups with the right aggregate.

Next: Connect tables with keys and relationships