Last updated
Understand customer retention behavior by analyzing the time gap between first and second orders.
Understand customer retention behavior by analyzing the time gap between first and second orders.
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
| Column | Type | Key / Notes |
|---|---|---|
| customer_id | INT | PK |
| join_date | DATE |
| Column | Type | Key / Notes |
|---|---|---|
| order_id | INT | PK |
| customer_id | INT | FK |
| order_date | DATE |
Customers — 8 rows
| customer_id | join_date |
|---|---|
| 101 | 2024-01-01 |
| 102 | 2024-01-05 |
| 103 | 2024-01-10 |
| 104 | 2024-01-12 |
| 105 | 2024-01-20 |
| 106 | 2024-02-01 |
| 107 | 2024-02-10 |
| 108 | 2024-02-15 |
Orders — 16 rows
| order_id | customer_id | order_date |
|---|---|---|
| 1 | 101 | 2024-01-05 |
| 2 | 101 | 2024-01-20 |
| 3 | 102 | 2024-01-10 |
| 4 | 102 | 2024-02-25 |
| 5 | 103 | 2024-01-15 |
| 6 | 103 | 2024-04-10 |
| 7 | 104 | 2024-01-18 |
| 8 | 104 | 2024-06-01 |
| 9 | 105 | 2024-01-25 |
| 10 | 105 | 2024-02-10 |
| 11 | 106 | 2024-02-05 |
| 12 | 106 | 2024-03-25 |
| 13 | 107 | 2024-02-15 |
| 14 | 107 | 2024-05-05 |
| 15 | 108 | 2024-02-20 |
| 16 | 108 | 2024-07-10 |
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_id | join_date | order_date | time_interval | drnk | cohort |
|---|---|---|---|---|---|
| 101 | 2024-01-01 | 2024-01-20 | 15 | 2 | Cohort 1 |
| 105 | 2024-01-20 | 2024-02-10 | 16 | 2 | Cohort 1 |
| … | … | … | … | … | … |