"Unlocking Advanced Data Analysis: Mastering LEAD, LAG, and Common Table Expressions"
Introduction
In this masterclass, we will delve into the world of advanced data analysis using SQL. We will explore two powerful concepts: Analytical Functions (LEAD, LAG) and Common Table Expressions (WITH, Recursive CTE). These tools will enable you to write more efficient and effective queries, uncover hidden insights, and take your data analysis skills to the next level.
7.2.1 Analytical Functions: LEAD and LAG
Analytical functions are used to analyze data in a result set. They allow you to perform calculations across rows and return values based on that analysis. Two essential analytical functions are LEAD and LAG.
- LEAD Function
The LEAD function returns the value of a column from a row that is a specified number of rows ahead of the current row. The syntax for the LEAD function is:
LEAD(column_name, offset, default_value) OVER (ORDER BY column_name)
column_name: The name of the column that you want to retrieve the value from.offset: The number of rows ahead of the current row that you want to retrieve the value from.default_value: The value to return if there is no row at the specified offset.
Example:
Suppose we have a table called sales with the following data:
| Month | Sales | | --- | --- | | January | 100 | | February | 120 | | March | 150 | | April | 180 |
To get the sales for the next month, we can use the LEAD function:
SELECT
Month,
Sales,
LEAD(Sales, 1, 0) OVER (ORDER BY Month) AS Next_Month_Sales
FROM
sales;
Result:
| Month | Sales | Next_Month_Sales | | --- | --- | --- | | January | 100 | 120 | | February | 120 | 150 | | March | 150 | 180 | | April | 180 | 0 |
- LAG Function
The LAG function returns the value of a column from a row that is a specified number of rows behind the current row. The syntax for the LAG function is:
LAG(column_name, offset, default_value) OVER (ORDER BY column_name)
column_name: The name of the column that you want to retrieve the value from.offset: The number of rows behind the current row that you want to retrieve the value from.default_value: The value to return if there is no row at the specified offset.
Example:
Using the same sales table, to get the sales for the previous month, we can use the LAG function:
SELECT
Month,
Sales,
LAG(Sales, 1, 0) OVER (ORDER BY Month) AS Previous_Month_Sales
FROM
sales;
Result:
| Month | Sales | Previous_Month_Sales | | --- | --- | --- | | January | 100 | 0 | | February | 120 | 100 | | March | 150 | 120 | | April | 180 | 150 |
7.2.2 Common Table Expressions (CTEs)
A Common Table Expression (CTE) is a temporary result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. CTEs are useful for simplifying complex queries and improving readability.
- Non-Recursive CTE
A non-recursive CTE is a CTE that does not reference itself. The syntax for a non-recursive CTE is:
WITH CTE_name AS (
SELECT ...
FROM ...
WHERE ...
)
SELECT ...
FROM CTE_name;
Example:
Suppose we have a table called employees with the following data:
| EmployeeID | Name | Department | | --- | --- | --- | | 1 | John | Sales | | 2 | Jane | Marketing | | 3 | Joe | Sales | | 4 | Sarah | Marketing |
To get the number of employees in each department, we can use a non-recursive CTE:
WITH DepartmentCounts AS (
SELECT
Department,
COUNT(*) AS EmployeeCount
FROM
employees
GROUP BY
Department
)
SELECT
Department,
EmployeeCount
FROM
DepartmentCounts;
Result:
| Department | EmployeeCount | | --- | --- | | Sales | 2 | | Marketing | 2 |
- Recursive CTE
A recursive CTE is a CTE that references itself. The syntax for a recursive CTE is:
WITH RECURSIVE CTE_name AS (
SELECT ... -- anchor query
UNION ALL
SELECT ... -- recursive query
)
SELECT ...
FROM CTE_name;
Example:
Suppose we have a table called categories with the following data:
| CategoryID | Name | ParentCategoryID | | --- | --- | --- | | 1 | Electronics | NULL | | 2 | Computers | 1 | | 3 | Laptops | 2 | | 4 | Desktops | 2 | | 5 | Clothing | NULL | | 6 | Shirts | 5 | | 7 | Pants | 5 |
To get the category hierarchy, we can use a recursive CTE:
WITH RECURSIVE CategoryHierarchy AS (
SELECT
CategoryID,
Name,
ParentCategoryID,
0 AS Level
FROM
categories
WHERE
ParentCategoryID IS NULL -- anchor query
UNION ALL
SELECT
c.CategoryID,
c.Name,
c.ParentCategoryID,
Level + 1
FROM
categories c
JOIN
CategoryHierarchy p ON c.ParentCategoryID = p.CategoryID -- recursive query
)
SELECT
CategoryID,
Name,
ParentCategoryID,
Level
FROM
CategoryHierarchy;
Result:
| CategoryID | Name | ParentCategoryID | Level | | --- | --- | --- | --- | | 1 | Electronics | NULL | 0 | | 2 | Computers | 1 | 1 | | 3 | Laptops | 2 | 2 | | 4 | Desktops | 2 | 2 | | 5 | Clothing | NULL | 0 | | 6 | Shirts | 5 | 1 | | 7 | Pants | 5 | 1 |
⚔️ YOUR MISSION
Mission:
You are a data analyst for an e-commerce company. You have a table called orders with the following columns:
OrderID(primary key)CustomerIDOrderDateTotal
Your mission is to write a query that returns the total sales for each customer, along with the total sales for the previous and next month.
Constraints:
- Use a recursive CTE to get the total sales for each customer.
- Use the LAG and LEAD functions to get the total sales for the previous and next month.
Deliverables:
- A SQL query that meets the requirements.
- A brief explanation of your approach.
Read the exercise prompt
CREATE TABLE orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
OrderDate DATE,
Total DECIMAL(10, 2)
);
INSERT INTO orders (OrderID, CustomerID, OrderDate, Total)
VALUES
(1, 1, '2022-01-01', 100.00),
(2, 1, '2022-01-15', 200.00),
(3, 2, '2022-02-01', 50.00),
(4, 2, '2022-02-15', 75.00),
(5, 1, '2022-03-01', 150.00),
(6, 1, '2022-03-15', 250.00);
