SQL
SQL Query: Aggregate and Filter Data with GROUP BY and HAVING
Summarize data using aggregate functions and `GROUP BY`, then filter these aggregated results with `HAVING` for powerful reporting and analytics.
SELECT
customer_id,
COUNT(order_id) AS total_orders,
SUM(total_amount) AS total_spending,
AVG(total_amount) AS average_order_value
FROM
orders
WHERE
order_date >= '2023-01-01'
GROUP BY
customer_id
HAVING
COUNT(order_id) > 5 AND SUM(total_amount) > 500
ORDER BY
total_spending DESC;
How it works: This query aggregates order data for customers, providing total orders, total spending, and average order value. The `GROUP BY customer_id` clause groups rows by each customer, allowing aggregate functions (`COUNT`, `SUM`, `AVG`) to operate on these groups. The `WHERE` clause filters individual rows *before* aggregation, while the `HAVING` clause filters the aggregated groups themselves, in this case, showing only customers who placed more than 5 orders and spent over 500 units since January 1st, 2023. This pattern is essential for reporting and analytical queries.