Menu

SQL Window Function Exercises and Solutions – Set 2

SQL window function exercises is designed to challenge your SQL muscle and help internalize data wrangling using window functions in SQL.

Written by Selva Prabhakaran | 13 min read

SQL window functions exercises is designed to challenge your SQL muscle and help internalize data wrangling using window functions in SQL. The questions are designed like fun puzzles, take your time and try to solve. By the end of this set, you should feel confident in solving the hardest SQL Window function problems.

If you haven’t read the tutorial yet, read SQL Window Functions – Must Read Guide.

Try solving hands-on in MySQL using the link provided in each question.

Author’s note: The solutions provided is (mostly) one of the several possible solutions. The goal is not to conform with the provided solution. Try reach the desired output shown.

Q1. Calculate the running total of sales.

Difficulty Level: Intermediate

Task:

From the sales table, calculate the running total of amount.

Input:

sale_idsale_dateamount
12022-01-01100
22022-01-05150
32022-02-15200
42022-02-20250
52022-03-10300

Desired Output:

sale_dateamountrunning_total
2022-01-01100100
2022-01-05150250
2022-02-15200450
2022-02-20250700
2022-03-103001000

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT sale_date, 
amount,
sum(amount) over (order by sale_date) as running_total
FROM sales;

## Q2. Get the difference between the current sale and the previous sale.

Difficulty Level: Intermediate

__Task:__

From the `sales` table, calculate the difference between the current sale and the previous sale.

__Input:__

| sale_id | sale_date | amount |
| ——- | ———- | —— |
| 1 | 2022-01-01 | 100 |
| 2 | 2022-01-05 | 150 |
| 3 | 2022-02-15 | 200 |
| 4 | 2022-02-20 | 250 |
| 5 | 2022-03-10 | 300 |

__Desired Output:__

| sale_date | amount | difference |
| ———- | —— | ———- |
| 2022-01-01 | 100 | 100 |
| 2022-01-05 | 150 | 50 |
| 2022-02-15 | 200 | 50 |
| 2022-02-20 | 250 | 50 |
| 2022-03-10 | 300 | 50 |

Solve Hands-On: [HERE](https://www.db-fiddle.com/f/xdbTd8VZi6GYaFFzNkDUHz/1), Table Schema and data: [Gist](https://gist.github.com/machinelearningplus/752971b25fcc4f15d53765c53d3ff3a1)

Show Solution

SELECT sale_date, 
		amount, 
        amount - LAG(amount, 1, 0) OVER (ORDER BY sale_date) AS difference 
FROM Sales;

Q3. Find the highest salary in each department

Difficulty Level: Intermediate

Task:

From the employees table, calculate the maximum salary in each department.

Input:

dept_idemp_idsalary
10150000
10255000
20360000
20465000

Desired Output:

dept_idemp_idsalarymax_salary
1015000055000
1025500055000
2036000065000
2046500065000

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT dept_id, 
        emp_id, 
        salary,
        MAX(salary) OVER (PARTITION BY dept_id) AS max_salary
FROM Employees;

Q4. Find the difference between the salary of an employee and the average salary of their department

Difficulty Level: Intermediate

Task:

From the employees table, find the difference between the salary of an employee and the average salary of their department.

Input:

dept_idemp_idsalary
10150000
10255000
20360000
20465000

Desired Output:

emp_iddept_idsalaryavg_dept_salarydiff_from_avg
1105000052500-2500
21055000525002500
3206000062500-2500
42065000625002500

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT emp_id, 
    dept_id, 
    salary,
    AVG(salary) OVER (PARTITION BY dept_id) AS avg_dept_salary,
    salary - AVG(salary) OVER (PARTITION BY dept_id) AS diff_from_avg
FROM Employees;

Q5. Calculate the 2-day moving average for the stock prices.

Difficulty Level: Intermediate

Task:

From the stockprices table, find the 2-day moving average.

Input:

dateprice
2022-01-01100.5
2022-01-02101.75
2022-01-03102
2022-01-04103
2022-01-05103.5
2022-01-06107

Desired Output:

datepricemoving_avg
2022-01-01100.5100.5
2022-01-02101.75101.125
2022-01-03102101.875
2022-01-04103102.5
2022-01-05103.5103.25
2022-01-06107105.25

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT date, price, 
       AVG(price) OVER (ORDER BY date ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS moving_avg
FROM StockPrices;

Q6. Calculate the difference in days between joining dates

Difficulty Level: Intermediate

Task:

Calculate the difference in days between each employee’s joining date and the previous employee’s joining date.

Input:

emp_idjoin_datesalary
12022-01-011000
22022-01-101100
32022-01-151200

Desired Output:

emp_idjoin_dateday_diff
12022-01-01NULL
22022-01-109
32022-01-155

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

with sub as (SELECT emp_id, 
		join_date,
        lag(join_date, 1) over (ORDER BY join_date) as prev_date
FROM employees)
select *, 
DATEDIFF(Date(join_date), date(prev_date)) AS day_diff
from sub;


Questions numbers Q7 onwards uses the same table as below. To avoid repetition, the input is printed only for Q7, please use the same for the full question set.

Q7. Find the cumulative sales amount for each product.

Difficulty Level: Intermediate

Task:

From Sales table, find the cumulative sales amount for each product.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0312120.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDSaleDateCumulativeSales
12023-01-01100
12023-01-02250
12023-01-03370
22023-01-0150
22023-01-02120
22023-01-03180
32023-01-0120
32023-01-0350

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT 
    ProductID,
    SaleDate,
    sum(SalesAmount) over(partition by ProductID order by SaleDate) AS CumulativeSales
FROM sales;

Q8. Compute the average sales for each product over all days.

Difficulty Level: Intermediate

Task:

From Sales table, find the cumulative sales amount for each product.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0312120.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDSaleDateCumulativeSales
12023-01-01100
12023-01-02250
12023-01-03370
22023-01-0150
22023-01-02120
22023-01-03180
32023-01-0120
32023-01-0350

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT 
    ProductID,
    SaleDate,
    sum(SalesAmount) over(partition by ProductID order by SaleDate) AS CumulativeSales
FROM sales;
```oyees)
select *, 
DATEDIFF(Date(join_date), date(prev_date)) AS day_diff
from sub;

Q9. Compute the average sales for each product over all days

Difficulty Level: Intermediate

Task:

From Sales table, compute the average sales for each product over all days.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0312120.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDAverageSales
1123.33
1123.33
1123.33
260
260
260
325
325

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT 
    ProductID,
    AVG(SalesAmount) OVER(PARTITION BY ProductID) AS AverageSales
FROM Sales;

Q10. Calculate the difference between the current day’s sales and the previous day’s sales

Difficulty Level: Intermediate

Task:

From Sales table, Calculate the difference between the current day’s sales and the previous day’s sales for each product.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0312120.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDSaleDateDifferenceFromPrevious
12023-01-01
12023-01-0250
12023-01-03-30
22023-01-01
22023-01-0220
22023-01-03-10
32023-01-01
32023-01-0310

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT 
    ProductID,
    SaleDate,
    SalesAmount - LAG(SalesAmount) OVER(PARTITION BY ProductID ORDER BY SaleDate) AS DifferenceFromPrevious
FROM Sales;

Q11. Get the next sale date for each product sale.

Difficulty Level: Intermediate

Task:

From Sales table, Get the next sale date for each product sale.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0312120.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDSaleDateNextSaleDate
12023-01-012023-01-02
12023-01-022023-01-03
12023-01-03
22023-01-012023-01-02
22023-01-022023-01-03
22023-01-03
32023-01-012023-01-03
32023-01-03

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT 
    ProductID,
    SaleDate,
    LEAD(SaleDate) OVER(PARTITION BY ProductID ORDER BY SaleDate) AS NextSaleDate
FROM Sales;

Q12. Find the total sales of the previous day for each product

Difficulty Level: Intermediate

Task:

From Sales table, Find the total sales of the previous day for each product.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0312120.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDSaleDatePreviousDaySales
12023-01-01
12023-01-02100
12023-01-03150
22023-01-01
22023-01-0250
22023-01-0370
32023-01-01
32023-01-0320

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution
SELECT 
    ProductID,
    SaleDate,
    LAG(SalesAmount) OVER(PARTITION BY ProductID ORDER BY SaleDate) AS PreviousDaySales
FROM Sales;

Q13. Calculate the average sales amount of the previous two days

Difficulty Level: Hard Task: From Sales table, for each sale, calculate the average sales amount of the previous two days (including the current day) for each product. Input:
SaleID ProductID SaleDate QuantitySold SalesAmount
1 1 2023-01-01 10 100.00
2 2 2023-01-01 5 50.00
3 3 2023-01-01 15 20.00
4 1 2023-01-02 15 150.00
5 2 2023-01-02 7 70.00
6 1 2023-01-03 12 120.00
7 2 2023-01-03 6 60.00
8 3 2023-01-03 16 30.00
Desired Output:
ProductID SaleDate AvgOfLastTwoDays
1 2023-01-01 100
1 2023-01-02 125
1 2023-01-03 135
2 2023-01-01 50
2 2023-01-02 60
2 2023-01-03 65
3 2023-01-01 20
3 2023-01-03 25
Solve Hands-On: HERE, Table Schema and data: Gist
Show Solution
SELECT 
    ProductID,
    SaleDate,
    AVG(SalesAmount) OVER(PARTITION BY ProductID ORDER BY SaleDate ROWS BETWEEN 1 PRECEDING AND CURRENT ROW) AS AvgOfLastTwoDays
FROM Sales;

Q14. Find the date of maximum sale

Difficulty Level: Hard

Task:

From Sales table, for each sale, get the sale date where maximum sales were made in the previous 2 days for each product.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0312120.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDSaleDateMaxSaleDateLastTwoDays
12023-01-022023-01-02
12023-01-032023-01-02
12023-01-012023-01-02
22023-01-022023-01-02
22023-01-032023-01-02
22023-01-012023-01-02
32023-01-032023-01-03
32023-01-012023-01-03

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT 
    ProductID,
    SaleDate,
    FIRST_VALUE(SaleDate) OVER(PARTITION BY ProductID ORDER BY SalesAmount DESC ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS MaxSaleDateLastTwoDays
FROM Sales;

Q15. Calculate the percentage contribution of each product's sale

Difficulty Level: Hard

Task:

From Sales table, Calculate the percentage contribution of each product's sale to the total sales of that day.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0312120.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDSaleDateMaxSaleDateLastTwoDays
12023-01-022023-01-02
12023-01-032023-01-02
12023-01-012023-01-02
22023-01-022023-01-02
22023-01-032023-01-02
22023-01-012023-01-02
32023-01-032023-01-03
32023-01-012023-01-03

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT 
    ProductID,
    SaleDate,
    SalesAmount,
    round((SalesAmount / SUM(SalesAmount) OVER(PARTITION BY SaleDate)) * 100, 2) AS PercentageContribution
FROM sales;

Q16. Calculate the third highest sales amount

Difficulty Level: Hard

Task:

For each product, get the third highest sales amount and its corresponding sale date.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0312120.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDSaleDateSalesAmount
12023-01-01100.00
22023-01-0150.00

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT 
    ProductID,
    SaleDate,
    SalesAmount
FROM (
    SELECT 
        ProductID,
        SaleDate,
        SalesAmount,
        DENSE_RANK() OVER(PARTITION BY ProductID ORDER BY SalesAmount DESC) AS rnk
    FROM sales
) AS T
WHERE rnk = 3;

Q17. Calculate the moving variance of the last 3 sales amounts for each product.

Difficulty Level: Hard

Task:

From sales table, calculate the moving variance of the last 3 sales amounts for each product.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0312120.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDSaleDateMovingVariance
12023-01-010
12023-01-02625
12023-01-03422.22222222222223
22023-01-010
22023-01-02100
22023-01-0366.66666666666667
32023-01-010
32023-01-0325

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT 
    ProductID,
    SaleDate,
    VARIANCE(SalesAmount) OVER(PARTITION BY ProductID ORDER BY SaleDate ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS MovingVariance
FROM sales;

Q18. Find the product that had the least sales amount difference compared to the previous day.

Difficulty Level: Hard

Task:

From sales table, For each sale date, find the product that had the least sales amount difference compared to the previous day.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0316160.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

SaleDateProductIDDiff
2023-01-011
2023-01-02220.00
2023-01-03210.00

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

WITH Differences AS (
    SELECT 
        ProductID,
        SaleDate,
        ABS(SalesAmount - LAG(SalesAmount) OVER(PARTITION BY ProductID ORDER BY SaleDate)) AS Diff
    FROM sales
)

SELECT 
    SaleDate,
    ProductID,
    Diff
FROM (
    SELECT 
        SaleDate,
        ProductID,
        Diff,
        ROW_NUMBER() OVER(PARTITION BY SaleDate ORDER BY Diff ASC) AS rnk
    FROM Differences
) AS T
WHERE rnk = 1;

Q19. Determine the average change in sales amounts

Difficulty Level: Hard

Task:

From sales table, for each product, determine the average change in sales amounts corresponding to the previous sale day.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0316160.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

PRODUCTIDAVGCHANGE
130.000000
25.000000
310.000000

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

with tbl as (SELECT 
    PRODUCTID,
    SALEDATE,
    (SalesAmount - LAG(SalesAmount, 1) OVER(PARTITION BY PRODUCTID ORDER BY SALEDATE)) AS diff,
    COUNT(*) over (PARTITION BY PRODUCTID) - 1 as num_changes
FROM sales),

tbl2 as (
SELECT PRODUCTID,
        max(SALEDATE) as SALEDATE,
        sum(diff) as SUMDIFF,
        max(num_changes) as TOTALCHANGES
        from tbl
group by ProductID)
SELECT PRODUCTID,
       SUMDIFF/TOTALCHANGES as AVGCHANGE
FROM tbl2;

Q20. Find the median sales amount for each product.

Difficulty Level: Hard

Task:

From sales table, for each product, determine the average change in sales amounts corresponding to the previous sale day.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0316160.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDMedian
1150.000000
260.000000
325.000000

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

WITH RankedSales AS (
    SELECT 
        ProductID,
        SalesAmount,
        ROW_NUMBER() OVER(PARTITION BY ProductID ORDER BY SalesAmount) AS rn,
        COUNT(*) OVER(PARTITION BY ProductID) AS cnt
    FROM sales
)

SELECT 
    ProductID,
    AVG(SalesAmount) AS Median
FROM RankedSales
WHERE rn IN (FLOOR((cnt+1)/2), CEIL((cnt+1)/2))
GROUP BY ProductID;

Q20. Find the difference from the average for each entry

Difficulty Level: Hard

Task:

For each sale, calculate the difference from the monthly average of the product's sales amount.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0316160.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDSaleDateSalesAmountDiffFromMonthlyAvg
12023-01-01100.00-36.666667
12023-01-02150.0013.333333
12023-01-03160.0023.333333
22023-01-0150.00-10.000000
22023-01-0270.0010.000000
22023-01-0360.000.000000
32023-01-0120.00-5.000000
32023-01-0330.005.000000

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT 
    ProductID,
    SaleDate,
    SalesAmount,
    SalesAmount - AVG(SalesAmount) OVER(PARTITION BY ProductID, EXTRACT(MONTH FROM SaleDate)) AS DiffFromMonthlyAvg
FROM sales;

Q21. Rank products by the variability

Difficulty Level: Hard

Task:

For each sale, calculate the difference from the monthly average of the product's sales amount.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0316160.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDSTDVVariabilityRank
132.14551
2102
37.07113

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT 
    ProductID,
    ROUND(STDDEV_SAMP(SalesAmount),4) as STDV,
    RANK() OVER(ORDER BY STDDEV_SAMP(SalesAmount) DESC) AS VariabilityRank
FROM sales
GROUP BY ProductID;

Q22. Calculate a 3-day centered moving average

Difficulty Level: Hard

Task:

Calculate a 3-day centered moving average for each product's sales amount.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0316160.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDSaleDateSalesAmountCenteredMovingAverage
12023-01-01100.00125.000000
12023-01-02150.00136.666667
12023-01-03160.00155.000000
22023-01-0150.0060.000000
22023-01-0270.0060.000000
22023-01-0360.0065.000000
32023-01-0120.0025.000000
32023-01-0330.0025.000000

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

SELECT 
    ProductID,
    SaleDate,
    SalesAmount,
    AVG(SalesAmount) OVER(PARTITION BY ProductID ORDER BY SaleDate ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) AS CenteredMovingAverage
FROM sales;

Q23. Determine if the sales amount of each product was above or below average

Difficulty Level: Hard

Task:

For each sale date, determine if the sales amount of each product was above or below its previous 3 days average.

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0316160.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDSaleDateSalesAmountComparisonToLast3Days
12023-01-01100.00Below
22023-01-0150.00Below
32023-01-0120.00Below
12023-01-02150.00Above
22023-01-0270.00Above
12023-01-03160.00Above
22023-01-0360.00Below
32023-01-0330.00Above

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

WITH threeDayAverage AS (
    SELECT 
        ProductID,
        SaleDate,
        AVG(SalesAmount) OVER(PARTITION BY ProductID ORDER BY SaleDate ROWS BETWEEN 2 PRECEDING AND 1 PRECEDING) AS avg_last_3_days
    FROM sales
)

SELECT 
    S.ProductID,
    S.SaleDate,
    S.SalesAmount,
    CASE 
        WHEN S.SalesAmount > A.avg_last_3_days THEN 'Above'
        ELSE 'Below'
    END AS ComparisonToLast3Days
FROM sales S
JOIN threeDayAverage A ON S.ProductID = A.ProductID AND S.SaleDate = A.SaleDate;

Q24. Calculate the cumulative sales growth rate

Difficulty Level: Hard

Task:

Calculate the cumulative sales growth rate for each product. (Sales growth rate from one day to the next is (TodaysSale−YesterdaysSale)/(YesterdaysSale).

Input:

SaleIDProductIDSaleDateQuantitySoldSalesAmount
112023-01-0110100.00
222023-01-01550.00
332023-01-011520.00
412023-01-0215150.00
522023-01-02770.00
612023-01-0316160.00
722023-01-03660.00
832023-01-031630.00

Desired Output:

ProductIDSaleDateSalesAmountcumulative_growth_rate
12023-01-01100.00
12023-01-02150.000.500000
12023-01-03160.000.566667
22023-01-0150.00
22023-01-0270.000.400000
22023-01-0360.000.257143
32023-01-0120.00
32023-01-0330.000.500000

Solve Hands-On: HERE, Table Schema and data: Gist

Show Solution

WITH GrowthRates AS (
    SELECT 
        ProductID,
        SaleDate,
        SalesAmount,
        (SalesAmount - LAG(SalesAmount) OVER(PARTITION BY ProductID ORDER BY SaleDate)) / LAG(SalesAmount) OVER(PARTITION BY ProductID ORDER BY SaleDate) AS growth_rate
    FROM sales
)

SELECT 
    ProductID,
    SaleDate,
    SalesAmount,
    SUM(growth_rate) OVER(PARTITION BY ProductID ORDER BY SaleDate) AS cumulative_growth_rate
FROM GrowthRates;

Next Steps

  1. Try the SQL Window Functions Set 1 if you haven't already done.
  2. To become real solid at SQL, the SQL courses (basic, intermediate and advanced) are included as part of the Machine Learning Plus - Complete Data Science University Access. Subscribe.
Free Course
Master Core Python — Your First Step into AI/ML

Build a strong Python foundation with hands-on exercises designed for aspiring Data Scientists and AI/ML Engineers.

Start Free Course
Trusted by 50,000+ learners
Related Course
Master SQL — Hands-On
Join 5,000+ students at edu.machinelearningplus.com
Explore Course
Free Callback - Limited Slots
Not Sure Which Course to Start With?
Talk to our AI Counsellors and Practitioners. We'll help you clear all your questions for your background and goals, bridging the gap between your current skills and a career in AI.
10-digit mobile number
📞
Thank You!
We'll Call You Soon!
Our learning advisor will reach out within 24 hours.
(Check your inbox too — we've sent a confirmation)
⚡ Before you go

Python.
SQL. NumPy.
All free.

Get the exact 10-course programming foundation that Data Science professionals use.

🐍
Core Python — from first line to expert level
📈
NumPy & Pandas — the #1 libraries every DS job needs
🗃️
SQL Levels I–III — basics to Window Functions
📄
Real industry data — Jupyter notebooks included
R A M S K
57,000+ students
★★★★★ Rated 4.9/5
⚡ Before you go
Python. SQL.
All Free.
R A M S K
57,000+ students  ★★★★★ 4.9/5
Get Free Access Now
10 courses. Real projects. Zero cost. No credit card.
New learners enrolling right now
🔒 100% free ☕ No spam, ever ✓ Instant access
🚀
You're in!
Check your inbox for your access link.
(Check Promotions or Spam if you don't see it)
Or start your first course right now:
Start Free Course →
Scroll to Top
Scroll to Top
Course Preview

Machine Learning A-Z™: Hands-On Python & R In Data Science

Free Sample Videos:

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science

Machine Learning A-Z™: Hands-On Python & R In Data Science