Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Aggregation in MySQL

Python MySQL Aggregation - E-Commerce Guide

Learn how to summarize and analyze data using aggregation functions in MySQL from Python.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
Read Time: 10 minutes Level: Intermediate Case Study: E-Commerce Platform Focus: Data Analysis & Reporting

E-Commerce Case Study: In this tutorial, you'll learn how to analyze your E-Commerce data using aggregation functions. You'll calculate total sales, average order values, product performance, and customer insights.

Python Focus: This tutorial focuses on executing aggregation queries from Python using mysql-connector-python. For pure SQL aggregation reference and optimization, we have a separate MySQL Aggregation Guide coming soon.

On this page:
  • What is Aggregation?
  • COUNT - Counting Records
  • SUM - Adding Values
  • AVG - Average Values
  • MAX and MIN
  • GROUP BY
  • HAVING
  • E-Commerce Python Examples
  • Best Practices
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • COUNT — counting products, orders, customers
  • SUM — calculating total revenue
  • AVG — average order value and product prices
  • MAX and MIN — highest and lowest values
  • GROUP BY — analyzing by category, customer, date
  • HAVING — filtering aggregated results

What is Aggregation?

Aggregation is the process of summarizing data to get insights. Instead of looking at individual records, you look at groups of records and calculate statistics like totals, averages, and counts.

COUNT

Number of records

SUM

Total of values

AVG

Average value

MAX

Highest value

MIN

Lowest value

GROUP BY

Group records

1

Aggregation in E-Commerce

# ============================================================
# AGGREGATION EXAMPLES IN E-COMMERCE
# ============================================================

# 1. COUNT - How many products?
SELECT COUNT(*) FROM products;

# 2. SUM - Total revenue
SELECT SUM(total_amount) FROM orders WHERE status = 'completed';

# 3. AVG - Average order value
SELECT AVG(total_amount) FROM orders;

# 4. MAX - Most expensive product
SELECT MAX(price) FROM products;

# 5. MIN - Cheapest product
SELECT MIN(price) FROM products;

# 6. GROUP BY - Sales by category
SELECT category, SUM(price) AS total_sales
FROM products
GROUP BY category;

Key point: Aggregation turns raw data into meaningful business insights.

Quick Check: What is aggregation? (Answer: Summarizing data to get insights like totals, averages, and counts)

COUNT - Counting Records

2

Counting in E-Commerce

# ============================================================
# COUNT FROM PYTHON
# ============================================================

import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="secret",
    database="ecommerce_db"
)

cursor = connection.cursor()

# ============================================================
# 1. COUNT ALL PRODUCTS
# ============================================================

cursor.execute("SELECT COUNT(*) FROM products")
count = cursor.fetchone()[0]
print(f"Total products: {count}")

# ============================================================
# 2. COUNT ELECTRONICS PRODUCTS
# ============================================================

cursor.execute("SELECT COUNT(*) FROM products WHERE category = 'Electronics'")
count = cursor.fetchone()[0]
print(f"Electronics products: {count}")

# ============================================================
# 3. COUNT CUSTOMERS WITH ORDERS
# ============================================================

cursor.execute("""
    SELECT COUNT(DISTINCT customer_id) 
    FROM orders
""")
count = cursor.fetchone()[0]
print(f"Customers with orders: {count}")

# ============================================================
# 4. COUNT PRODUCTS WITH STOCK
# ============================================================

cursor.execute("SELECT COUNT(*) FROM products WHERE stock_quantity > 0")
count = cursor.fetchone()[0]
print(f"Products in stock: {count}")

cursor.close()
connection.close()

COUNT key points:

  • COUNT(*) — counts all rows
  • COUNT(DISTINCT) — counts unique values
  • COUNT with WHERE — counts matching rows
  • Useful for metrics — number of products, customers, orders

Quick Check: What does COUNT(DISTINCT customer_id) count? (Answer: The number of unique customers)

SUM - Adding Values

3

Calculating Totals in E-Commerce

# ============================================================
# SUM FROM PYTHON
# ============================================================

import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="secret",
    database="ecommerce_db"
)

cursor = connection.cursor()

# ============================================================
# 1. TOTAL REVENUE
# ============================================================

cursor.execute("SELECT SUM(total_amount) FROM orders WHERE status = 'completed'")
total = cursor.fetchone()[0] or 0
print(f"Total revenue: ${total}")

# ============================================================
# 2. REVENUE BY CATEGORY
# ============================================================

cursor.execute("""
    SELECT p.category, SUM(oi.quantity * oi.unit_price) AS revenue
    FROM products p
    JOIN order_items oi ON p.product_id = oi.product_id
    GROUP BY p.category
""")
results = cursor.fetchall()
print("Revenue by category:")
for r in results:
    print(f"  {r[0]}: ${r[1]}")

# ============================================================
# 3. TOTAL UNITS SOLD
# ============================================================

cursor.execute("SELECT SUM(quantity) FROM order_items")
total_units = cursor.fetchone()[0]
print(f"Total units sold: {total_units}")

# ============================================================
# 4. TOTAL CUSTOMER SPENDING
# ============================================================

cursor.execute("""
    SELECT c.first_name, c.last_name, COALESCE(SUM(o.total_amount), 0) AS total_spent
    FROM customers c
    LEFT JOIN orders o ON c.customer_id = o.customer_id
    GROUP BY c.customer_id
""")
results = cursor.fetchall()
print("\nCustomer spending:")
for r in results:
    print(f"  {r[0]} {r[1]}: ${r[2]}")

cursor.close()
connection.close()

SUM key points:

  • SUM(column) — adds up values
  • SUM with JOIN — calculates across tables
  • COALESCE — handles NULL values
  • Useful for revenue — total sales, category revenue

Quick Check: What does COALESCE(SUM(total_amount), 0) do? (Answer: Returns 0 instead of NULL when there are no orders)

AVG - Average Values

4

Calculating Averages in E-Commerce

# ============================================================
# AVG FROM PYTHON
# ============================================================

import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="secret",
    database="ecommerce_db"
)

cursor = connection.cursor()

# ============================================================
# 1. AVERAGE ORDER VALUE
# ============================================================

cursor.execute("SELECT AVG(total_amount) FROM orders WHERE status = 'completed'")
avg = cursor.fetchone()[0] or 0
print(f"Average order value: ${avg:.2f}")

# ============================================================
# 2. AVERAGE PRICE BY CATEGORY
# ============================================================

cursor.execute("""
    SELECT category, AVG(price) AS avg_price
    FROM products
    GROUP BY category
""")
results = cursor.fetchall()
print("Average price by category:")
for r in results:
    print(f"  {r[0]}: ${r[1]:.2f}")

# ============================================================
# 3. AVERAGE PRODUCT RATING
# ============================================================

cursor.execute("""
    SELECT p.product_name, AVG(r.rating) AS avg_rating
    FROM products p
    JOIN reviews r ON p.product_id = r.product_id
    GROUP BY p.product_id
""")
results = cursor.fetchall()
print("\nProduct ratings:")
for r in results:
    print(f"  {r[0]}: {r[1]:.1f} stars")

# ============================================================
# 4. AVERAGE QUANTITY PER ORDER
# ============================================================

cursor.execute("""
    SELECT AVG(quantity) AS avg_items
    FROM order_items
""")
avg_items = cursor.fetchone()[0] or 0
print(f"Average items per order: {avg_items:.1f}")

cursor.close()
connection.close()

AVG key points:

  • AVG(column) — calculates average
  • AVG with GROUP BY — averages per group
  • Ignores NULL — NULL values are not included
  • Useful for benchmarks — average order, rating, price

Quick Check: What does AVG do with NULL values? (Answer: It ignores them)

MAX and MIN

5

Finding Extremes in E-Commerce

# ============================================================
# MAX AND MIN FROM PYTHON
# ============================================================

import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="secret",
    database="ecommerce_db"
)

cursor = connection.cursor()

# ============================================================
# 1. HIGHEST AND LOWEST PRICES
# ============================================================

cursor.execute("SELECT MAX(price), MIN(price) FROM products")
max_price, min_price = cursor.fetchone()
print(f"Highest price: ${max_price}")
print(f"Lowest price: ${min_price}")

# ============================================================
# 2. MOST EXPENSIVE PRODUCT IN EACH CATEGORY
# ============================================================

cursor.execute("""
    SELECT category, product_name, price
    FROM products
    WHERE (category, price) IN (
        SELECT category, MAX(price)
        FROM products
        GROUP BY category
    )
""")
results = cursor.fetchall()
print("\nMost expensive product in each category:")
for r in results:
    print(f"  {r[0]}: {r[1]} - ${r[2]}")

# ============================================================
# 3. BEST AND WORST SELLER
# ============================================================

cursor.execute("""
    SELECT p.product_name, SUM(oi.quantity) AS total_sold
    FROM products p
    JOIN order_items oi ON p.product_id = oi.product_id
    GROUP BY p.product_id
    ORDER BY total_sold DESC
""")
results = cursor.fetchall()
print("\nProduct sales ranking:")
for i, r in enumerate(results[:5], 1):
    print(f"  #{i}: {r[0]} - {r[1]} units")

# ============================================================
# 4. HIGHEST AND LOWEST RATED PRODUCTS
# ============================================================

cursor.execute("""
    SELECT p.product_name, AVG(r.rating) AS avg_rating
    FROM products p
    JOIN reviews r ON p.product_id = r.product_id
    GROUP BY p.product_id
    HAVING avg_rating = (SELECT MAX(avg_rating) FROM (
        SELECT AVG(rating) AS avg_rating
        FROM reviews
        GROUP BY product_id
    ) AS t)
""")
best = cursor.fetchall()
print(f"\nHighest rated product: {best[0][0]} - {best[0][1]:.1f} stars")

cursor.close()
connection.close()

MAX and MIN key points:

  • MAX — finds the highest value
  • MIN — finds the lowest value
  • Useful for extremes — best sellers, most expensive
  • Can use with GROUP BY — per category, per customer

Quick Check: What do MAX and MIN find? (Answer: The highest and lowest values)

GROUP BY - Grouping Data

6

Analyzing Data by Groups

# ============================================================
# GROUP BY FROM PYTHON
# ============================================================

import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="secret",
    database="ecommerce_db"
)

cursor = connection.cursor()

# ============================================================
# 1. SALES BY CATEGORY
# ============================================================

query = """
    SELECT p.category,
           COUNT(DISTINCT o.order_id) AS order_count,
           SUM(oi.quantity) AS units_sold,
           SUM(oi.quantity * oi.unit_price) AS revenue
    FROM products p
    JOIN order_items oi ON p.product_id = oi.product_id
    JOIN orders o ON oi.order_id = o.order_id
    WHERE o.status = 'completed'
    GROUP BY p.category
    ORDER BY revenue DESC
"""
cursor.execute(query)
results = cursor.fetchall()

print("Sales by category:")
for r in results:
    print(f"  {r[0]}: {r[1]} orders, {r[2]} units, ${r[3]:.2f}")

# ============================================================
# 2. MONTHLY SALES
# ============================================================

query = """
    SELECT DATE_FORMAT(order_date, '%Y-%m') AS month,
           COUNT(order_id) AS order_count,
           SUM(total_amount) AS revenue
    FROM orders
    WHERE status = 'completed'
    GROUP BY DATE_FORMAT(order_date, '%Y-%m')
    ORDER BY month DESC
"""
cursor.execute(query)
results = cursor.fetchall()

print("\nMonthly sales:")
for r in results:
    print(f"  {r[0]}: {r[1]} orders, ${r[2]:.2f}")

# ============================================================
# 3. CUSTOMER SPENDING
# ============================================================

query = """
    SELECT c.first_name, c.last_name,
           COUNT(o.order_id) AS order_count,
           COALESCE(SUM(o.total_amount), 0) AS total_spent
    FROM customers c
    LEFT JOIN orders o ON c.customer_id = o.customer_id
    GROUP BY c.customer_id
    ORDER BY total_spent DESC
"""
cursor.execute(query)
results = cursor.fetchall()

print("\nCustomer spending:")
for r in results:
    print(f"  {r[0]} {r[1]}: {r[2]} orders, ${r[3]:.2f}")

cursor.close()
connection.close()

GROUP BY key points:

  • GROUP BY column — groups by that column
  • Aggregation functions — used on grouped data
  • ORDER BY — sort results
  • Useful for reports — sales by category, monthly revenue

Quick Check: What does GROUP BY do? (Answer: Groups records with the same value so you can apply aggregation functions)

HAVING - Filtering Groups

7

Filtering After GROUP BY

# ============================================================
# HAVING FROM PYTHON
# ============================================================

import mysql.connector

connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="secret",
    database="ecommerce_db"
)

cursor = connection.cursor()

# ============================================================
# 1. CATEGORIES WITH REVENUE OVER $1000
# ============================================================

query = """
    SELECT p.category,
           SUM(oi.quantity * oi.unit_price) AS revenue
    FROM products p
    JOIN order_items oi ON p.product_id = oi.product_id
    GROUP BY p.category
    HAVING revenue > 1000
    ORDER BY revenue DESC
"""
cursor.execute(query)
results = cursor.fetchall()

print("Categories with revenue over $1000:")
for r in results:
    print(f"  {r[0]}: ${r[1]:.2f}")

# ============================================================
# 2. CUSTOMERS WHO SPENT OVER $500
# ============================================================

query = """
    SELECT c.first_name, c.last_name,
           COALESCE(SUM(o.total_amount), 0) AS total_spent
    FROM customers c
    LEFT JOIN orders o ON c.customer_id = o.customer_id
    GROUP BY c.customer_id
    HAVING total_spent > 500
    ORDER BY total_spent DESC
"""
cursor.execute(query)
results = cursor.fetchall()

print("\nCustomers who spent over $500:")
for r in results:
    print(f"  {r[0]} {r[1]}: ${r[2]:.2f}")

# ============================================================
# 3. PRODUCTS WITH MORE THAN 5 REVIEWS
# ============================================================

query = """
    SELECT p.product_name,
           COUNT(r.review_id) AS review_count,
           AVG(r.rating) AS avg_rating
    FROM products p
    JOIN reviews r ON p.product_id = r.product_id
    GROUP BY p.product_id
    HAVING review_count > 5
    ORDER BY review_count DESC
"""
cursor.execute(query)
results = cursor.fetchall()

print("\nProducts with more than 5 reviews:")
for r in results:
    print(f"  {r[0]}: {r[1]} reviews, {r[2]:.1f} stars")

cursor.close()
connection.close()

HAVING key points:

  • HAVING — filters groups after GROUP BY
  • Uses aggregated values — SUM, AVG, COUNT in condition
  • Different from WHERE — WHERE filters before grouping
  • Useful for thresholds — revenue over $1000, customers with >5 orders

Quick Check: What is the difference between WHERE and HAVING? (Answer: WHERE filters rows before grouping; HAVING filters groups after grouping)

E-Commerce Python Examples

8

Complete E-Commerce Analytics

# ============================================================
# COMPLETE E-COMMERCE ANALYTICS
# ============================================================

import mysql.connector

class ECommerceAnalytics:
    """E-Commerce analytics using aggregation"""
    
    def __init__(self, db_config):
        self.db_config = db_config
        self.connection = None
        self.cursor = None
    
    def connect(self):
        try:
            self.connection = mysql.connector.connect(**self.db_config)
            self.cursor = self.connection.cursor()
            return True
        except Exception as e:
            print(f"Connection failed: {e}")
            return False
    
    # ============================================================
    # DASHBOARD METRICS
    # ============================================================
    
    def get_dashboard_metrics(self):
        """Get all dashboard metrics in one query"""
        query = """
            SELECT 
                (SELECT COUNT(*) FROM customers) AS total_customers,
                (SELECT COUNT(*) FROM products WHERE stock_quantity > 0) AS products_in_stock,
                (SELECT COUNT(*) FROM orders WHERE status = 'pending') AS pending_orders,
                (SELECT COALESCE(SUM(total_amount), 0) FROM orders WHERE status = 'completed') AS total_revenue,
                (SELECT COALESCE(AVG(total_amount), 0) FROM orders WHERE status = 'completed') AS avg_order_value
        """
        self.cursor.execute(query)
        return self.cursor.fetchone()
    
    # ============================================================
    # SALES REPORTS
    # ============================================================
    
    def get_sales_by_category(self):
        """Get sales grouped by category"""
        query = """
            SELECT p.category,
                   COUNT(DISTINCT o.order_id) AS order_count,
                   SUM(oi.quantity) AS units_sold,
                   SUM(oi.quantity * oi.unit_price) AS revenue,
                   AVG(oi.unit_price) AS avg_price
            FROM products p
            JOIN order_items oi ON p.product_id = oi.product_id
            JOIN orders o ON oi.order_id = o.order_id
            WHERE o.status = 'completed'
            GROUP BY p.category
            ORDER BY revenue DESC
        """
        self.cursor.execute(query)
        return self.cursor.fetchall()
    
    def get_monthly_revenue(self, months=6):
        """Get monthly revenue for last N months"""
        query = """
            SELECT DATE_FORMAT(order_date, '%Y-%m') AS month,
                   COUNT(order_id) AS order_count,
                   SUM(total_amount) AS revenue,
                   AVG(total_amount) AS avg_order
            FROM orders
            WHERE status = 'completed'
            AND order_date >= DATE_SUB(CURDATE(), INTERVAL %s MONTH)
            GROUP BY DATE_FORMAT(order_date, '%Y-%m')
            ORDER BY month DESC
        """
        self.cursor.execute(query, (months,))
        return self.cursor.fetchall()
    
    # ============================================================
    # CUSTOMER REPORTS
    # ============================================================
    
    def get_customer_lifetime_value(self, min_orders=1):
        """Get customer lifetime value"""
        query = """
            SELECT c.customer_id, c.first_name, c.last_name,
                   COUNT(o.order_id) AS order_count,
                   COALESCE(SUM(o.total_amount), 0) AS lifetime_value,
                   COALESCE(AVG(o.total_amount), 0) AS avg_order_value
            FROM customers c
            LEFT JOIN orders o ON c.customer_id = o.customer_id
            GROUP BY c.customer_id
            HAVING order_count >= %s
            ORDER BY lifetime_value DESC
        """
        self.cursor.execute(query, (min_orders,))
        return self.cursor.fetchall()
    
    def get_top_customers(self, limit=10):
        """Get top customers by spending"""
        query = """
            SELECT c.first_name, c.last_name, c.email,
                   COUNT(o.order_id) AS order_count,
                   COALESCE(SUM(o.total_amount), 0) AS total_spent
            FROM customers c
            LEFT JOIN orders o ON c.customer_id = o.customer_id
            GROUP BY c.customer_id
            ORDER BY total_spent DESC
            LIMIT %s
        """
        self.cursor.execute(query, (limit,))
        return self.cursor.fetchall()
    
    # ============================================================
    # PRODUCT REPORTS
    # ============================================================
    
    def get_product_performance(self):
        """Get product performance metrics"""
        query = """
            SELECT p.product_id, p.product_name, p.category, p.price,
                   COALESCE(SUM(oi.quantity), 0) AS total_sold,
                   COALESCE(SUM(oi.quantity * oi.unit_price), 0) AS revenue,
                   COALESCE(AVG(r.rating), 0) AS avg_rating,
                   COUNT(DISTINCT r.review_id) AS review_count,
                   p.stock_quantity
            FROM products p
            LEFT JOIN order_items oi ON p.product_id = oi.product_id
            LEFT JOIN reviews r ON p.product_id = r.product_id
            GROUP BY p.product_id
            ORDER BY revenue DESC
        """
        self.cursor.execute(query)
        return self.cursor.fetchall()
    
    def get_out_of_stock_products(self):
        """Get products out of stock"""
        query = """
            SELECT product_name, category, stock_quantity
            FROM products
            WHERE stock_quantity = 0
        """
        self.cursor.execute(query)
        return self.cursor.fetchall()
    
    # ============================================================
    # ANALYTICS SUMMARY
    # ============================================================
    
    def get_summary_report(self):
        """Get comprehensive analytics summary"""
        report = {}
        
        # Basic metrics
        self.cursor.execute("SELECT COUNT(*) FROM customers")
        report['total_customers'] = self.cursor.fetchone()[0]
        
        self.cursor.execute("SELECT COUNT(*) FROM products")
        report['total_products'] = self.cursor.fetchone()[0]
        
        self.cursor.execute("SELECT COUNT(*) FROM orders")
        report['total_orders'] = self.cursor.fetchone()[0]
        
        self.cursor.execute("SELECT COALESCE(SUM(total_amount), 0) FROM orders WHERE status = 'completed'")
        report['total_revenue'] = self.cursor.fetchone()[0]
        
        self.cursor.execute("SELECT COALESCE(AVG(total_amount), 0) FROM orders WHERE status = 'completed'")
        report['avg_order_value'] = self.cursor.fetchone()[0]
        
        self.cursor.execute("SELECT COUNT(DISTINCT customer_id) FROM orders")
        report['customers_with_orders'] = self.cursor.fetchone()[0]
        
        self.cursor.execute("SELECT COUNT(*) FROM orders WHERE status = 'pending'")
        report['pending_orders'] = self.cursor.fetchone()[0]
        
        return report
    
    def display_results(self, results, title="Results"):
        """Display results"""
        if not results:
            print(f"\n{title}: No results")
            return
        print(f"\n{title}:")
        print("-" * 60)
        if isinstance(results, tuple):
            print(f"  {results}")
        else:
            for row in results:
                print(f"  {row}")
    
    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()

# ============================================================
# DEMONSTRATION
# ============================================================

db_config = {
    "host": "localhost",
    "user": "root",
    "password": "secret",
    "database": "ecommerce_db"
}

analytics = ECommerceAnalytics(db_config)

if analytics.connect():
    
    print("=" * 60)
    print("E-COMMERCE ANALYTICS DASHBOARD")
    print("=" * 60)
    
    # 1. Dashboard metrics
    print("\n1. DASHBOARD METRICS")
    metrics = analytics.get_dashboard_metrics()
    if metrics:
        print(f"  Total Customers: {metrics[0]}")
        print(f"  Products in Stock: {metrics[1]}")
        print(f"  Pending Orders: {metrics[2]}")
        print(f"  Total Revenue: ${metrics[3]:.2f}")
        print(f"  Average Order Value: ${metrics[4]:.2f}")
    
    # 2. Sales by category
    print("\n2. SALES BY CATEGORY")
    results = analytics.get_sales_by_category()
    for r in results:
        print(f"  {r[0]}: {r[1]} orders, {r[2]} units, ${r[3]:.2f}")
    
    # 3. Monthly revenue
    print("\n3. MONTHLY REVENUE")
    results = analytics.get_monthly_revenue(3)
    for r in results:
        print(f"  {r[0]}: {r[1]} orders, ${r[2]:.2f} (avg ${r[3]:.2f})")
    
    # 4. Top customers
    print("\n4. TOP CUSTOMERS")
    results = analytics.get_top_customers(3)
    for r in results:
        print(f"  {r[0]} {r[1]}: {r[2]} orders, ${r[3]:.2f}")
    
    # 5. Summary report
    print("\n5. SUMMARY REPORT")
    report = analytics.get_summary_report()
    for key, value in report.items():
        print(f"  {key}: {value}")
    
    analytics.close()

This analytics example shows:

  • Dashboard metrics with multiple aggregations
  • Sales analysis by category and month
  • Customer lifetime value calculations
  • Product performance tracking
  • Comprehensive business reports

Quick Check: What is customer lifetime value? (Answer: The total amount a customer has spent over their entire relationship with the business)

Best Practices

9

Aggregation Best Practices

# ============================================================
# AGGREGATION BEST PRACTICES
# ============================================================

print("1. USE ALIASES FOR AGGREGATED COLUMNS")
print("   - SUM(total) AS total_revenue")
print("   - AVG(price) AS avg_price")
print("   - Improves readability")

print("\n2. HANDLE NULL VALUES")
print("   - Use COALESCE(SUM(amount), 0)")
print("   - NULL + number = NULL")

print("\n3. FILTER BEFORE GROUPING")
print("   - Use WHERE to filter rows")
print("   - Reduces data to aggregate")

print("\n4. USE HAVING FOR GROUP FILTERS")
print("   - Filter groups after aggregation")
print("   - HAVING SUM(amount) > 1000")

print("\n5. USE DISTINCT WHEN NEEDED")
print("   - COUNT(DISTINCT customer_id)")
print("   - Counts unique values")

print("\n6. OPTIMIZE WITH INDEXES")
print("   - Index columns used in GROUP BY")
print("   - Speeds up aggregation")

print("\n7. USE DATE FUNCTIONS WISELY")
print("   - DATE_FORMAT() for grouping by month")
print("   - GROUP BY DATE(order_date)")

print("\n8. TEST WITH EXPLAIN")
print("   - Check execution plans")
print("   - Identify performance issues")

Summary of best practices:

  • Use aliases — for readability
  • Handle NULL — use COALESCE
  • Filter before grouping — use WHERE
  • Use HAVING for groups — filter after aggregation
  • Use DISTINCT — for unique counts

Quick Check: What is the difference between WHERE and HAVING in aggregation? (Answer: WHERE filters rows before grouping; HAVING filters groups after grouping)

Try It Yourself

Experiment with aggregation functions in the editor below.

Loading Pyodide... 0%
Python Code Editor
========================================
AGGREGATION - PRACTICE
========================================

1. BASIC AGGREGATION
----------------------------------------
Total Products: 6
Total Revenue: $1429.96
Average Price: $421.49
Highest Price: $1099.99
Lowest Price: $29.99

2. GROUP BY - Products by Category
----------------------------------------
Electronics: 2 products
Footwear: 2 products
Clothing: 2 products

3. COMPLETE ANALYSIS
----------------------------------------
┌─────────────────┬──────────────────────────────────────────────┐
│ Function │ Result │
├─────────────────┼──────────────────────────────────────────────┤
│ COUNT │ Number of records │
│ SUM │ Total value │
│ AVG │ Average value │
│ MAX │ Highest value │
│ MIN │ Lowest value │
│ GROUP BY │ Group by category, customer, date │
│ HAVING │ Filter groups after aggregation │
└─────────────────┴──────────────────────────────────────────────┘

Aggregation turns data into insights!
🏆

You've Got It!

You now understand aggregation in MySQL from Python. You can use COUNT, SUM, AVG, MAX, MIN, GROUP BY, and HAVING for E-Commerce analytics.

Quick Quiz

Test what you've learned:

1. What does COUNT(*) do?
2. What does SUM() do?
3. What does GROUP BY do?
4. What is the difference between WHERE and HAVING?
5. Which function finds the highest value?

Frequently Asked Questions

What is the difference between COUNT(*) and COUNT(column)? ▼

COUNT(*) counts all rows, including those with NULL values. COUNT(column) counts only non-null values in that specific column.

Can I use multiple aggregation functions together? ▼

Yes, you can use multiple aggregation functions in one SELECT statement. For example: SELECT COUNT(*), SUM(amount), AVG(price) FROM sales

What is a common interview question about aggregation? ▼

Common questions include: "Explain the difference between WHERE and HAVING," "What is the difference between COUNT(*) and COUNT(column)?" and "How do you group data in MySQL?"

How does AVG() handle NULL values? ▼

AVG() ignores NULL values when calculating the average. It only considers non-null values in the calculation.

Will this conflict with future pure MySQL tutorials? ▼

No. This tutorial focuses on executing aggregation from Python with mysql-connector. Future MySQL tutorials will focus on SQL syntax and optimization with different titles and URLs.

Where to Go From Here

Now that you understand aggregation, check out these related topics:

Case Study

See all concepts in a complete E-Commerce project.

Learn More →

Practice Assignments

Test your knowledge with practical exercises.

Practice Now →

JOIN Operations

Learn how to combine data from multiple tables.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Python Lists and Dictionaries Interview Questions
  • Python OOP Interview Questions
  • SQL Set Operators Interview Questions
Previous: JOIN Operations Next: Case Study →