Ivy Professional School
Rating
Learning/SQL Data Drill #7

Cohort Analysis

Last updated

Understand customer retention behavior by analyzing the time gap between first and second orders.

SQLIntermediateViewWindow FunctionsLAGDENSE_RANK

Your Objective

Understand customer retention behavior by analyzing the time gap between first and second orders.

The Setup

Your dataset contains two tables from an e-commerce platform: 1. A Customers table with customer_id and join_date for each customer 2. An Orders table with order_id, customer_id, and order_date for each order

Table Schema

Customers
ColumnTypeKey / Notes
customer_idINTPK
join_dateDATE
Orders
ColumnTypeKey / Notes
order_idINTPK
customer_idINTFK
order_dateDATE

Sample Data

Customers — 8 rows

customer_idjoin_date
1012024-01-01
1022024-01-05
1032024-01-10
1042024-01-12
1052024-01-20
1062024-02-01
1072024-02-10
1082024-02-15

Orders — 16 rows

order_idcustomer_idorder_date
11012024-01-05
21012024-01-20
31022024-01-10
41022024-02-25
51032024-01-15
61032024-04-10
71042024-01-18
81042024-06-01
91052024-01-25
101052024-02-10
111062024-02-05
121062024-03-25
131072024-02-15
141072024-05-05
151082024-02-20
161082024-07-10

Your Task

This drill has three steps: 1. Create Cohort Table — Create a SQL view named Cohort_Table that uses LAG() and TIMESTAMPDIFF to find the gap between each customer's first and second order, then assigns a cohort label: • Cohort 1: 0–30 days • Cohort 2: 31–60 days • Cohort 3: 61–90 days • Cohort 4: More than 90 days 2. Percentage by Cohort — What percentage of customers fall in each cohort? Your result table should have: cohort, percentage. 3. Average Days per Cohort — What is the average time_interval for each cohort? Your result table should have: cohort, avg_time_interval.

Your output should look like this (partial example):

customer_idjoin_dateorder_datetime_intervaldrnkcohort
1012024-01-012024-01-20152Cohort 1
1052024-01-202024-02-10162Cohort 1
………………

Hints

  • →Use LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) to get the previous order date per customer.
  • →TIMESTAMPDIFF(DAY, lag_value, order_date) calculates the gap in days between consecutive orders.
  • →DENSE_RANK() OVER (PARTITION BY customer_id ORDER BY order_date) numbers orders sequentially — filter WHERE drnk = 2 to isolate each customer's second order.
  • →Wrap the LAG + TIMESTAMPDIFF + DENSE_RANK logic in a CTE, then apply the CASE statement in the outer SELECT to assign cohort labels before creating the view.
Explore Enterprise Solutions