Practice and reinforce the concepts from Lesson 5
You're analyzing quarterly sales for an online store and need to calculate totals, averages, and counts by category. This requires GROUP BY and aggregate functions.
Scenario: Management needs a sales summary report for Q4 planning.
-- Simple sales table
CREATE TABLE sales (
id INT PRIMARY KEY,
product_name VARCHAR(50),
category VARCHAR(30),
quantity INT,
price DECIMAL(8,2),
sale_date DATE
);
-- Sample data (10 sales records)
INSERT INTO sales VALUES
(1, 'iPhone 14', 'Electronics', 2, 999.00, '2024-01-15'),
(2, 'Coffee Mug', 'Home', 5, 12.99, '2024-01-16'),
(3, 'Laptop Pro', 'Electronics', 1, 1899.00, '2024-01-17'),
(4, 'Desk Chair', 'Home', 3, 149.99, '2024-01-18'),
(5, 'Headphones', 'Electronics', 4, 79.99, '2024-01-19'),
(6, 'Table Lamp', 'Home', 2, 34.99, '2024-01-20'),
(7, 'Tablet', 'Electronics', 1, 599.00, '2024-01-21'),
(8, 'Bookshelf', 'Home', 1, 89.99, '2024-01-22'),
(9, 'Smart Watch', 'Electronics', 3, 299.00, '2024-01-23'),
(10, 'Throw Pillow', 'Home', 6, 19.99, '2024-01-24');
GROUP BY combines rows with the same values and lets you calculate summary statistics.
Basic Pattern:
SELECT column, AGGREGATE_FUNCTION(column)
FROM table
GROUP BY column;
Key Aggregate Functions:
COUNT()
- Count rowsSUM()
- Add up valuesAVG()
- Calculate averageMAX()
- Find maximumMIN()
- Find minimum-- Sales by category
SELECT category, COUNT(*) as num_sales
FROM sales
GROUP BY category;
-- Total revenue by category
SELECT category,
COUNT(*) as num_sales,
SUM(quantity * price) as total_revenue,
AVG(quantity * price) as avg_sale_amount
FROM sales
GROUP BY category
ORDER BY total_revenue DESC;
-- Categories with more than $500 total revenue
SELECT category,
SUM(quantity * price) as total_revenue
FROM sales
GROUP BY category
HAVING SUM(quantity * price) > 500
ORDER BY total_revenue DESC;
Run your queries and check:
Expected output for revenue by category:
Electronics | 5 | 4673.95 | 934.79
Home | 5 | 659.89 | 131.98
For advanced aggregation patterns including window functions, complex grouping sets, and performance optimization, see:
/* Reference link removed - file doesn't exist **[Aggregations Advanced Theory →](./Reference/Database-Theory/Aggregations-Advanced.mdx)** */Topics covered there:
Complete this activity and submit your work through the Activity Submission Form