Ivy Professional School
Rating
Learning/SQL Data Drill #4

Performance Trends

Last updated

Use window functions and aggregations to analyze monthly sales performance, AOV trends, and returning customer behavior.

SQLIntermediateWindow FunctionsLAGCTEGROUP BY

Your Objective

Use window functions and aggregations to analyze monthly sales performance, AOV trends, and returning customer behavior.

The Setup

Your dataset contains two tables from an e-commerce platform: 1. An orders table with order_id, customer_id, order_date, and status for each order 2. An order_items table with item_id, order_id, quantity, and line_amount for each line item in the order

Table Schema

orders
ColumnTypeKey / Notes
order_idINTPK
customer_idINTFK
order_dateDATE
statusVARCHAR(20)
order_items
ColumnTypeKey / Notes
item_idINTPK
order_idINTFK
quantityINT
line_amountDECIMAL(10,2)

Sample Data

orders — sample

order_idcustomer_idorder_datestatus
11012024-01-05Completed
21022024-01-12Completed
31032024-01-18Cancelled
41042024-01-25Completed
51052024-02-03Completed
61062024-02-14Completed
71072024-03-02Completed
81082024-03-19Completed
91092024-04-08Completed
101102024-04-22Completed

order_items — sample

item_idorder_idquantityline_amount
1133,600.00
2122,400.00
3256,000.00
4311,100.00
5444,800.00
6522,500.00
7633,100.00
861900.00
9767,200.00
10834,500.00

Your Task

This drill has two tasks: 1. Monthly Sales Trend — How have total quantity sold and revenue changed month-over-month in the last 12 months? Your result table should have: month_year, revenue, MoM_rev, qty, MoM_qty_sold. 2. Average Order Value (AOV) Trend — How is AOV (revenue ÷ number of orders) trending by month? Your result table should have: month_year, AOV, MoM_AOV.

Your output should look like this (partial example):

month_yearrevenueMoM_revqtyMoM_qty_sold
January, 2024124,500NULL1,840NULL
February, 2024118,200-5.06%1,710-7.07%
……………

Hints

  • →Use a CTE to aggregate orders joined with order_items by year and month. Exclude cancelled orders using WHERE status <> 'Cancelled'.
  • →LAG() accesses the previous row's value in a defined ORDER BY — no self-join needed. Use ORDER BY yr, mnth (integer columns) rather than the formatted month string to ensure correct chronological ordering.
  • →For AOV (Query 2), compute revenue ÷ COUNT(DISTINCT order_id) inside the CTE, then apply LAG() in the outer query to find the month-over-month change.
Explore Enterprise Solutions