Conditional Aggregation Pattern in SQL
📖 Scenario: You work for a small online store. The store keeps track of orders in a table called orders. Each order has a status which can be 'completed', 'pending', or 'cancelled'. You want to find out how many orders are in each status for each customer.
🎯 Goal: Create an SQL query that uses conditional aggregation to count the number of orders by status for each customer.
📋 What You'll Learn
Create a table called
orders with columns order_id (integer), customer_id (integer), and status (text).Insert exactly these rows into
orders: (1, 101, 'completed'), (2, 101, 'pending'), (3, 102, 'completed'), (4, 103, 'cancelled'), (5, 101, 'completed').Write a query that selects
customer_id and counts of orders with status 'completed', 'pending', and 'cancelled' using conditional aggregation.Use
SUM(CASE WHEN ... THEN 1 ELSE 0 END) for counting each status.💡 Why This Matters
🌍 Real World
Stores and businesses often need to summarize data by categories, like counting orders by status for each customer.
💼 Career
Knowing conditional aggregation is essential for data analysts and database developers to create meaningful reports and insights.
Progress0 / 4 steps