SQL
Summarize Data with Aggregate Functions and GROUP BY
Calculate summary statistics like total counts, sums, or averages for groups of records, useful for reporting and analytics, using SQL aggregate functions and GROUP BY.
SELECT
customer_id,
COUNT(order_id) AS total_orders,
SUM(total_amount) AS total_spent,
AVG(total_amount) AS avg_order_value
FROM
orders
GROUP BY
customer_id
HAVING
COUNT(order_id) > 5
ORDER BY
total_spent DESC;
How it works: This query demonstrates how to group rows that have the same values in specified columns into a set of summary rows by using the GROUP BY clause. It then applies aggregate functions (COUNT, SUM, AVG) to each group. Here, it calculates the total orders, total amount spent, and average order value for each customer. The HAVING clause filters these groups, showing only customers who have placed more than 5 orders, ordered by their total spending.