SQL
Grouping Data and Filtering Groups with HAVING
Master SQL's GROUP BY clause to aggregate data and use HAVING to filter these aggregated results, for example, to find users with multiple orders.
SELECT user_id, COUNT(id) AS total_orders, SUM(total_amount) AS total_spent
FROM orders
GROUP BY user_id
HAVING COUNT(id) > 5
ORDER BY total_spent DESC;
How it works: This snippet groups the 'orders' table by 'user_id' to calculate the total number of orders and the sum of the total amount spent for each user. The 'HAVING' clause is then used to filter these grouped results, showing only users who have placed more than 5 orders. This is a powerful technique for generating summary reports and identifying specific groups based on aggregated values.