Advanced Aggregation Techniques
In this final step, we'll explore more advanced aggregation techniques combining everything we've learned. We'll create comprehensive sales reports that demonstrate the power of these tools together.
Let's create a comprehensive sales analysis:
SELECT
category,
COUNT(DISTINCT product_name) as unique_products,
COUNT(*) as total_transactions,
SUM(quantity) as total_quantity,
ROUND(AVG(quantity), 1) as avg_quantity_per_sale,
ROUND(MIN(unit_price), 2) as min_price,
ROUND(MAX(unit_price), 2) as max_price,
ROUND(SUM(quantity * unit_price), 2) as total_revenue
FROM sales
GROUP BY category
ORDER BY total_revenue DESC;
Explanation:
- Creates a complete category performance overview
- Uses DISTINCT to count unique products within each category
- Combines multiple aggregate functions for comprehensive analysis
- Shows price ranges with MIN and MAX
- Calculates average quantities and total revenue
- Results are ordered by revenue to highlight top performers
Let's analyze sales performance by region:
SELECT
region,
COUNT(DISTINCT category) as categories_sold,
COUNT(DISTINCT product_name) as unique_products,
SUM(quantity) as total_quantity,
ROUND(SUM(quantity * unit_price), 2) as total_revenue,
ROUND(SUM(quantity * unit_price) / SUM(quantity), 2) as avg_price_per_unit
FROM sales
GROUP BY region
HAVING total_revenue > 1000
ORDER BY total_revenue DESC;
Explanation:
- Groups sales data by geographical regions
- Shows product diversity with DISTINCT counts
- Calculates total revenue and quantity metrics
- avg_price_per_unit is computed using revenue divided by quantity
- HAVING filters out regions with lower revenue
- Helps identify strongest and weakest performing regions
Daily Trends Analysis
Let's create a daily sales trend report:
SELECT
sale_date,
COUNT(DISTINCT category) as categories_sold,
COUNT(DISTINCT product_name) as unique_products,
COUNT(*) as transactions,
SUM(quantity) as total_quantity,
ROUND(SUM(quantity * unit_price), 2) as daily_revenue,
ROUND(AVG(quantity * unit_price), 2) as avg_transaction_value
FROM sales
GROUP BY sale_date
ORDER BY sale_date;
Explanation:
- Tracks daily sales performance metrics
- Shows product and category diversity per day
- Counts daily transactions and quantities
- Calculates daily revenue and average transaction value
- Chronological ordering helps identify trends
- Useful for spotting patterns and seasonal effects
- Can help with inventory planning and staffing decisions