SQL
Group and Filter Aggregated Data with HAVING Clause
Learn to group database records and apply filters on aggregated results using `GROUP BY` and `HAVING` for powerful reporting and analytical queries.
SELECT
c.customer_id,
c.customer_name,
COUNT(o.order_id) AS total_orders,
SUM(o.total_amount) AS total_spent
FROM
customers c
JOIN
orders o ON c.customer_id = o.customer_id
GROUP BY
c.customer_id, c.customer_name
HAVING
SUM(o.total_amount) > 1000 AND COUNT(o.order_id) >= 5
ORDER BY
total_spent DESC;
How it works: This query aggregates customer order data to provide insights into their purchasing behavior. It joins `customers` and `orders` tables, then uses `GROUP BY` to summarize `total_orders` and `total_spent` for each customer. The `HAVING` clause filters these aggregated results, showing only customers who have spent more than 1000 and placed at least 5 orders, making it ideal for identifying high-value customers.