SQL
Aggregate Data with GROUP BY and Filter Groups with HAVING
Summarize and filter data groups based on aggregate conditions using SQL's GROUP BY and HAVING clauses, perfect for reporting and analytics.
SELECT
customer_id,
COUNT(order_id) AS total_orders,
SUM(total_amount) AS total_spent
FROM
orders
GROUP BY
customer_id
HAVING
COUNT(order_id) > 5 AND SUM(total_amount) > 1000
ORDER BY
total_spent DESC;
How it works: This query aggregates order data by `customer_id`, calculating the total number of orders and total amount spent for each customer. The `GROUP BY` clause groups rows with the same `customer_id`. The `HAVING` clause then filters these *groups* based on aggregate conditions, showing only customers who have placed more than 5 orders and spent over 1000 units. This is essential for identifying high-value customers or analyzing customer segments.