SQL

Aggregating Data with GROUP BY and HAVING

Summarize and filter grouped data using `GROUP BY` for aggregation and `HAVING` to filter results based on aggregate conditions, like total sales per customer.

SELECT customer_id, COUNT(order_id) AS total_orders, SUM(amount) AS total_spent
FROM orders
WHERE order_date >= '2023-01-01'
GROUP BY customer_id
HAVING SUM(amount) > 500
ORDER BY total_spent DESC;
How it works: This query calculates the total number of orders and the total amount spent for each customer since January 1, 2023. `GROUP BY customer_id` groups the rows by customer, and `HAVING SUM(amount) > 500` then filters these aggregated groups, showing only customers who spent more than 500. The `WHERE` clause filters individual rows before grouping, while `HAVING` filters results after grouping and aggregation.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs