-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcohortAnalysis_Adventurework.sql
More file actions
349 lines (322 loc) · 11.8 KB
/
Copy pathcohortAnalysis_Adventurework.sql
File metadata and controls
349 lines (322 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
--====cohort analysis
-- objective of this project? Analyze customer retention, Customer Lifetime Value (CLV), churn patterns, and cohort behavior.
--------
-- Analyze customer retention Rate
-- 1. Identify the Cohort for Each Customer
-- This query finds the first purchase date (month) for each customer:
WITH FirstPurchaseCohort AS (
SELECT
CustomerID,
DATEPART(YEAR, MIN(OrderDate)) AS CohortYear, -- Get the Year of the first purchase
DATEPART(MONTH, MIN(OrderDate)) AS CohortMonth -- Get the Month of the first purchase
FROM Sales.SalesOrderHeader
GROUP BY CustomerID
)
SELECT * FROM FirstPurchaseCohort
ORDER BY CohortYear ASC, CohortMonth ASC;
--2. Combine Cohort Data with Orders
--Join the cohort data with order data to track customer purchases over time:
WITH FirstPurchaseCohort AS (
SELECT
CustomerID,
DATEPART(YEAR, MIN(OrderDate)) AS CohortYear, -- Get the Year of the first purchase
DATEPART(MONTH, MIN(OrderDate)) AS CohortMonth -- Get the Month of the first purchase
FROM Sales.SalesOrderHeader
GROUP BY CustomerID
),
CustomerOrders AS (
SELECT
fpc.CustomerID,
fpc.CohortYear,
fpc.CohortMonth,
DATEPART(YEAR, soh.OrderDate) AS OrderYear,
DATEPART(MONTH, soh.OrderDate) AS OrderMonth
FROM FirstPurchaseCohort fpc
JOIN Sales.SalesOrderHeader soh
ON fpc.CustomerID = soh.CustomerID
)
SELECT * FROM CustomerOrders;
-- => The SQL query you have right now is only tracking the first purchase and subsequent second purchases (or any repeat purchases) in terms of the first purchase cohort.
-- 3. Count Active Customers per Cohort Over Time
-- Now, calculate the number of active customers in each cohort for each month:
WITH FirstPurchaseCohort AS (
SELECT
CustomerID,
DATEPART(YEAR, MIN(OrderDate)) AS CohortYear, -- Get the Year of the first purchase
DATEPART(MONTH, MIN(OrderDate)) AS CohortMonth -- Get the Month of the first purchase
FROM Sales.SalesOrderHeader
GROUP BY CustomerID
),
CustomerOrders AS (
SELECT
fpc.CustomerID,
fpc.CohortYear,
fpc.CohortMonth,
DATEPART(YEAR, soh.OrderDate) AS OrderYear,
DATEPART(MONTH, soh.OrderDate) AS OrderMonth
FROM FirstPurchaseCohort fpc
JOIN Sales.SalesOrderHeader soh
ON fpc.CustomerID = soh.CustomerID
),
CohortAnalysis AS (
SELECT
CohortYear,
CohortMonth,
OrderYear,
OrderMonth,
COUNT(DISTINCT CustomerID) AS ActiveCustomers
FROM CustomerOrders
GROUP BY CohortYear, CohortMonth, OrderYear, OrderMonth
)
SELECT
CohortYear,
CohortMonth,
OrderYear,
OrderMonth,
ActiveCustomers
FROM CohortAnalysis
ORDER BY CohortYear, CohortMonth, OrderYear, OrderMonth;
--=> This output helps you track the retention and activity of customers based on their first purchase in January 2011
--=> For example: In June 2011 (OrderYear = 2011, OrderMonth = 6), 7 unique customers from the January 2011 cohort made a purchase.
-- 4. Calculate Retention Rates
-- To calculate retention rates, divide the number of active customers by the cohort size:
WITH FirstPurchaseCohort AS (
SELECT
CustomerID,
DATEPART(YEAR, MIN(OrderDate)) AS CohortYear, -- Get the Year of the first purchase
DATEPART(MONTH, MIN(OrderDate)) AS CohortMonth -- Get the Month of the first purchase
FROM Sales.SalesOrderHeader
GROUP BY CustomerID
),
CustomerOrders AS (
SELECT
fpc.CustomerID,
fpc.CohortYear,
fpc.CohortMonth,
DATEPART(YEAR, soh.OrderDate) AS OrderYear,
DATEPART(MONTH, soh.OrderDate) AS OrderMonth,
ROW_NUMBER() OVER (PARTITION BY fpc.CustomerID ORDER BY soh.OrderDate) AS OrderRank
FROM FirstPurchaseCohort fpc
JOIN Sales.SalesOrderHeader soh
ON fpc.CustomerID = soh.CustomerID
),
ReturnCustomers AS (
SELECT
CustomerID,
CohortYear,
CohortMonth,
OrderYear,
OrderMonth
FROM CustomerOrders
WHERE OrderRank > 1 -- This filters out first-time purchasers (only return customers)
),
CohortSizes AS (
SELECT
CohortYear,
CohortMonth,
COUNT(DISTINCT CustomerID) AS CohortSize
FROM FirstPurchaseCohort
GROUP BY CohortYear, CohortMonth
),
CohortAnalysis AS (
SELECT
fpc.CohortYear,
fpc.CohortMonth,
DATEPART(YEAR, soh.OrderDate) AS OrderYear,
DATEPART(MONTH, soh.OrderDate) AS OrderMonth,
COUNT(DISTINCT soh.CustomerID) AS ActiveCustomers,
COUNT(DISTINCT rc.CustomerID) AS ReturnCustomers -- Count only return customers
FROM FirstPurchaseCohort fpc
JOIN Sales.SalesOrderHeader soh
ON fpc.CustomerID = soh.CustomerID
LEFT JOIN ReturnCustomers rc
ON soh.CustomerID = rc.CustomerID
AND DATEPART(YEAR, soh.OrderDate) = rc.OrderYear
AND DATEPART(MONTH, soh.OrderDate) = rc.OrderMonth
GROUP BY fpc.CohortYear, fpc.CohortMonth, DATEPART(YEAR, soh.OrderDate), DATEPART(MONTH, soh.OrderDate)
)
SELECT
ca.CohortYear,
ca.CohortMonth,
ca.OrderYear,
ca.OrderMonth,
ca.ActiveCustomers,
ca.ReturnCustomers, -- Show return customers
cs.CohortSize,
ROUND(ca.ReturnCustomers * 1.0 / cs.CohortSize, 2) AS RetentionRate -- Round retention rate to 2 decimal places
FROM CohortAnalysis ca
JOIN CohortSizes cs
ON ca.CohortYear = cs.CohortYear AND ca.CohortMonth = cs.CohortMonth
ORDER BY ca.CohortYear, ca.CohortMonth, ca.OrderYear, ca.OrderMonth;
--=====pivot retention
WITH FirstPurchaseCohort AS (
SELECT
CustomerID,
MIN(DATEFROMPARTS(YEAR(OrderDate), MONTH(OrderDate), 1)) AS CohortDate
FROM Sales.SalesOrderHeader
GROUP BY CustomerID
),
CustomerOrders AS (
SELECT
fpc.CustomerID,
fpc.CohortDate,
DATEFROMPARTS(YEAR(soh.OrderDate), MONTH(soh.OrderDate), 1) AS OrderMonthDate,
DATEDIFF(MONTH, fpc.CohortDate, soh.OrderDate) AS CohortIndex
FROM FirstPurchaseCohort fpc
JOIN Sales.SalesOrderHeader soh
ON fpc.CustomerID = soh.CustomerID
),
CohortSizes AS (
SELECT
CohortDate,
COUNT(DISTINCT CustomerID) AS CohortSize
FROM FirstPurchaseCohort
GROUP BY CohortDate
),
RetentionAnalysis AS (
SELECT
co.CohortDate,
co.CohortIndex,
COUNT(DISTINCT co.CustomerID) AS RetainedCustomers
FROM CustomerOrders co
GROUP BY co.CohortDate, co.CohortIndex
)
SELECT
ra.CohortDate,
cs.CohortSize,
ra.CohortIndex,
ra.RetainedCustomers,
ROUND(ra.RetainedCustomers * 1.0 / cs.CohortSize, 2) AS RetentionRate
FROM RetentionAnalysis ra
JOIN CohortSizes cs
ON ra.CohortDate = cs.CohortDate
ORDER BY ra.CohortDate, ra.CohortIndex;
--=======================
-- Analyze Customer Lifetime Value (CLV)
-- 1. Identify the Cohort for Each Customer
WITH FirstPurchaseCohort AS (
SELECT
CustomerID,
DATEPART(YEAR, MIN(OrderDate)) AS CohortYear, -- Get the Year of the first purchase
DATEPART(MONTH, MIN(OrderDate)) AS CohortMonth -- Get the Month of the first purchase
FROM Sales.SalesOrderHeader
GROUP BY CustomerID
),
-- 2. Combine Cohort Data with Orders and Calculate Revenue
CustomerOrders AS (
SELECT
fpc.CustomerID,
fpc.CohortYear,
fpc.CohortMonth,
DATEPART(YEAR, soh.OrderDate) AS OrderYear,
DATEPART(MONTH, soh.OrderDate) AS OrderMonth,
DATEDIFF(MONTH,
DATEFROMPARTS(fpc.CohortYear, fpc.CohortMonth, 1),
DATEFROMPARTS(DATEPART(YEAR, soh.OrderDate), DATEPART(MONTH, soh.OrderDate), 1)
) AS MonthsSinceFirstPurchase,
soh.TotalDue AS Revenue
FROM FirstPurchaseCohort fpc
JOIN Sales.SalesOrderHeader soh
ON fpc.CustomerID = soh.CustomerID
),
-- 3. Aggregate Revenue by Cohort and Month
CohortRevenue AS (
SELECT
CohortYear,
CohortMonth,
MonthsSinceFirstPurchase,
SUM(Revenue) AS TotalRevenue
FROM CustomerOrders
GROUP BY CohortYear, CohortMonth, MonthsSinceFirstPurchase
),
-- 4. Calculate Cumulative Revenue (CLV) for Each Cohort
CohortCLV AS (
SELECT
CohortYear,
CohortMonth,
MonthsSinceFirstPurchase,
TotalRevenue,
SUM(TotalRevenue) OVER (
PARTITION BY CohortYear, CohortMonth
ORDER BY MonthsSinceFirstPurchase
) AS CumulativeRevenue
FROM CohortRevenue
)
-- 5. Output the CLV Analysis
SELECT
CohortYear,
CohortMonth,
MonthsSinceFirstPurchase,
TotalRevenue AS MonthlyRevenue,
CumulativeRevenue AS LifetimeValue
FROM CohortCLV
ORDER BY CohortYear, CohortMonth, MonthsSinceFirstPurchase;
--=> The MonthsSinceFirstPurchase = 5 means that the customer made their first purchase in January and now, five months later, were looking at their purchase in June 2011.
/*
Explain Columns:
cohortyear: The year when the cohort made their first purchase. In this case, its 2011.
cohortmonth: The month when the cohort made their first purchase. Here, its January 2011.
monthssincefirstpurchase: This shows how many months have passed since the customer's first purchase in the cohort. For example, 5 means five months after the first purchase in January.
monthlyrevenue: This is the revenue generated in the given month (since the first purchase) for customers in this cohort. Its the total revenue of all customers from that cohort who made purchases in that month.
lifetimevalue: This is the cumulative revenue generated from this cohort up to and including the current month. Its the sum of monthlyrevenue up until the current month.
*/
--=========================
-- code to sort Top cohorts by highest CLV
-- 1. Identify the Cohort for Each Customer
WITH FirstPurchaseCohort AS (
SELECT
CustomerID,
DATEPART(YEAR, MIN(OrderDate)) AS CohortYear, -- Get the Year of the first purchase
DATEPART(MONTH, MIN(OrderDate)) AS CohortMonth -- Get the Month of the first purchase
FROM Sales.SalesOrderHeader
GROUP BY CustomerID
),
-- 2. Combine Cohort Data with Orders and Calculate Revenue
CustomerOrders AS (
SELECT
fpc.CustomerID,
fpc.CohortYear,
fpc.CohortMonth,
DATEPART(YEAR, soh.OrderDate) AS OrderYear,
DATEPART(MONTH, soh.OrderDate) AS OrderMonth,
DATEDIFF(MONTH,
DATEFROMPARTS(fpc.CohortYear, fpc.CohortMonth, 1),
DATEFROMPARTS(DATEPART(YEAR, soh.OrderDate), DATEPART(MONTH, soh.OrderDate), 1)
) AS MonthsSinceFirstPurchase,
soh.TotalDue AS Revenue
FROM FirstPurchaseCohort fpc
JOIN Sales.SalesOrderHeader soh
ON fpc.CustomerID = soh.CustomerID
),
-- 3. Aggregate Revenue by Cohort and Month
CohortRevenue AS (
SELECT
CohortYear,
CohortMonth,
MonthsSinceFirstPurchase,
SUM(Revenue) AS TotalRevenue
FROM CustomerOrders
GROUP BY CohortYear, CohortMonth, MonthsSinceFirstPurchase
),
-- 4. Calculate Cumulative Revenue (CLV) for Each Cohort
CohortCLV AS (
SELECT
CohortYear,
CohortMonth,
MonthsSinceFirstPurchase,
TotalRevenue,
SUM(TotalRevenue) OVER (
PARTITION BY CohortYear, CohortMonth
ORDER BY MonthsSinceFirstPurchase
) AS CumulativeRevenue
FROM CohortRevenue
)
-- 5. Output the CLV Analysis and Cohort Comparison
SELECT
CohortYear,
CohortMonth,
SUM(TotalRevenue) AS TotalRevenue,
MAX(CumulativeRevenue) AS MaxCLV
FROM CohortCLV
GROUP BY CohortYear, CohortMonth
ORDER BY MaxCLV DESC; -- Top cohorts by highest CLV