The finance team wants to know how many paid or refunded orders each customer has placed, using data from the orders table.
Prepare a customer-level summary that includes only customers with at least one paid or refunded order.
Ordering: Results can be returned in any order.
Returncustomer_idorder_count· any row order
About this problem
You practise filtering rows before you group them. Finance wants, for each customer in orders, the number of orders whose status is 'paid' or 'refunded', returned as customer_id and order_count. Only customers with at least one such order appear. The skill is choosing the grain correctly, one row per customer with a single count, and deciding which orders enter that count before the aggregation runs.
The mistake this pattern is named for is adding status to the GROUP BY. With GROUP BY customer_id, status, a customer with one paid and one refunded order comes back as two rows, each with a count of 1, instead of one row with 2. Every number looks plausible, and the counts even add up to the right total, but they answer a different question: orders per customer per status. The other slip is the filter. Leaving it out counts pending, delivered and NULL-status orders as well, and trying to apply it in HAVING fails because status is no longer a single value per customer group. Check that no customer appears twice in your output.
Read the lesson: Aggregation & GROUP BY (P04) →