-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1_customer_segmentation.sql
More file actions
40 lines (40 loc) · 1.12 KB
/
1_customer_segmentation.sql
File metadata and controls
40 lines (40 loc) · 1.12 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
WITH customer_total_ltv AS (
SELECT
customerkey,
cleaned_name,
sum(net_revenue) AS total_ltv
FROM cohort_analysis
GROUP BY
customerkey,
cleaned_name
ORDER BY customerkey
),
pcntl_cont AS (
SELECT
PERCENTILE_CONT(0.25) WITHIN GROUP (ORDER BY total_ltv) AS "25th_pcntl",
PERCENTILE_CONT(0.75) WITHIN GROUP (ORDER BY total_ltv) AS "75th_pcntl"
FROM customer_total_ltv cl
),
customer_category AS (
SELECT
customer_total_ltv.*,
case
WHEN total_ltv < "25th_pcntl" THEN '0_low_value'
WHEN total_ltv >= "75th_pcntl" THEN '2_high_vale'
ELSE '1_medium_value'
END AS customer_segment
FROM
pcntl_cont pc,
customer_total_ltv
)
SELECT
customer_segment,
count(customerkey) AS NO_of_customers,
sum(total_ltv) AS net_revenue_contribution,
(sum(total_ltv)/count(customer_segment)) AS avg_ltv,
round(100*(count(customerkey)/SUM(count(customerkey)) over()),2) AS percent_of_customers
FROM customer_category
GROUP BY
customer_segment
ORDER BY
customer_segment DESC;