-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnnual Customer Activity Growth Analysis.sql
More file actions
90 lines (81 loc) · 2 KB
/
Annual Customer Activity Growth Analysis.sql
File metadata and controls
90 lines (81 loc) · 2 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
--Subtask 1
--Average number of monthly active users for each year
WITH
mau_of_year AS (
SELECT
year,
round(AVG(mau), 2) AS avg_mau
FROM (
SELECT
date_part('year', o.order_purchase_timestamp) AS year,
date_part('month', o.order_purchase_timestamp) AS month,
COUNT(DISTINCT c.customer_unique_id) AS mau
FROM orders o
JOIN customers c
ON o.customer_id = c.customer_id
GROUP BY 1, 2
) subq
GROUP BY 1),
--Subtask 2
--number of new customers every year
newcust_of_year AS (
SELECT
date_part('year', first_order) AS year,
COUNT(customer_unique_id) AS new_customers
FROM
(SELECT
c.customer_unique_id,
MIN(o.order_purchase_timestamp) AS first_order
FROM orders AS o
JOIN customers AS c
ON c.customer_id = o.customer_id
GROUP BY 1) AS subq
GROUP BY 1
ORDER BY 1 ASC),
--Subtask 3
--number of customers who make purchases more than once (repeat orders) in each year
repeat_of_year AS (
SELECT
year,
COUNT(DISTINCT customer) AS repeat_customer
FROM(
SELECT
date_part('year', o.order_purchase_timestamp) AS year,
c.customer_unique_id AS customer,
COUNT(order_id) AS total_transaction
FROM customers c
JOIN orders o
ON c.customer_id=o.customer_id
GROUP BY 1,2
HAVING COUNT(order_id) > 1
)subq
GROUP BY 1),
--Subtask 4
--average number of orders made by customers for each year
avg_freq_of_year AS (
SELECT
year,
round(AVG(total_transaction),4) AS avg_transaction
FROM(
SELECT
date_part('year', o.order_purchase_timestamp) AS year,
c.customer_unique_id AS customer,
COUNT(order_id) AS total_transaction
FROM customers c
JOIN orders o
ON c.customer_id=o.customer_id
GROUP BY 1,2
)subq
GROUP BY 1)
--Subtask 5
--Merge the tables above
SELECT
moy.year,
moy.avg_mau,
noy.new_customers,
roy.repeat_customer,
afoy.avg_transaction
FROM mau_of_year AS moy
JOIN newcust_of_year AS noy ON moy.year = noy.year
JOIN repeat_of_year AS roy ON roy.year = moy.year
JOIN avg_freq_of_year AS afoy ON afoy.year = moy.year;