SQL
Perform Conditional Aggregation with CASE Statements
Master conditional aggregation in SQL by using CASE statements within aggregate functions to sum or count data based on specific conditions.
SELECT
product_category,
SUM(CASE WHEN status = 'completed' THEN amount ELSE 0 END) AS total_completed_sales,
COUNT(CASE WHEN status = 'pending' THEN 1 ELSE NULL END) AS pending_orders_count
FROM orders
GROUP BY product_category;
How it works: This query demonstrates how to perform conditional aggregations. It sums `amount` only for orders with a 'completed' status and counts orders with a 'pending' status, grouped by `product_category`. The `CASE` statement selectively includes values in the aggregate functions based on specified conditions.