1
+ /*
2
+ CUSTOMER REPORT
3
+
4
+ Purpose:
5
+ - This report consolidates key customer metrics and behaviours.
6
+
7
+ Highlights:
8
+ 1. Gathers essential fields such as names,ages,and transaction details.
9
+ 2. Segments customers into categories (VIP,Regular,New) and age groups.
10
+ 3.Aggregates customer-level metrics:
11
+ -total orders
12
+ -total sales
13
+ -total quantity purchased
14
+ -total products
15
+ -lifespan (in months)
16
+ 4.Calculates valueable KPIs:
17
+ - recency(months since last order)
18
+ -average order value
19
+ -average monthly spend
20
+ */
21
+
22
+ CREATE VIEW gold .report_customers AS
23
+ WITH base_query AS (
24
+ /* Base query : Retrieves core olumns from tables */
25
+ SELECT
26
+ f .order_number ,
27
+ f .product_key ,
28
+ f .order_date ,
29
+ f .sales_amount ,
30
+ f .quantity ,
31
+ c .customer_key ,
32
+ c .customer_number ,
33
+ CONCAT(c .first_name , ' ' , c .last_name ) AS customer_name,
34
+ DATEDIFF(year, c .birthdate , GETDATE()) age
35
+ FROM
36
+ gold .fact_sales f
37
+ LEFT JOIN gold .dim_customers c
38
+ ON c .customer_key = f .customer_key
39
+ WHERE order_date IS NOT NULL
40
+ )
41
+ ,customer_aggregation AS (
42
+ SELECT
43
+ customer_key,
44
+ customer_number,
45
+ customer_name,
46
+ age,
47
+ COUNT (DISTINCT order_number) AS total_orders,
48
+ SUM (sales_amount) AS total_sales,
49
+ SUM (quantity) AS total_quantity,
50
+ COUNT (DISTINCT product_key) AS total_products,
51
+ MAX (order_date) AS last_order_date,
52
+ DATEDIFF(month,MIN (order_date), MAX (order_date)) AS lifespan
53
+ FROM base_query
54
+ GROUP BY
55
+ customer_key,
56
+ customer_number,
57
+ customer_name,
58
+ age
59
+ )
60
+
61
+ SELECT
62
+ customer_key,
63
+ customer_number,
64
+ customer_name,
65
+ age,
66
+ CASE
67
+ WHEN age < 20 THEN ' Under 20'
68
+ WHEN age between 20 and 29 THEN ' 20-29'
69
+ WHEN age between 30 and 39 THEN ' 30-39'
70
+ WHEN age between 40 and 49 THEN ' 40-49'
71
+ ELSE ' 50 and above'
72
+ END AS age_group,
73
+ CASE
74
+ WHEN lifespan >= 12 AND total_sales > 5000 THEN ' VIP'
75
+ WHEN lifespan >= 12 AND total_sales <= 5000 THEN ' Regular'
76
+ ELSE ' New'
77
+ END AS customer_segment,
78
+ last_order_date,
79
+ DATEDIFF(month,last_order_date,GETDATE()) AS resency,
80
+ total_orders,
81
+ total_sales,
82
+ total_quantity,
83
+ total_products,
84
+ lifespan,
85
+ -- Compute average order value( AVO)
86
+ CASE WHEN total_sales = 0 THEN 0
87
+ ELSE total_sales / total_orders
88
+ END AS avg_order_value,
89
+ -- Compute average monthly spend
90
+ CASE WHEN lifespan = 0 THEN total_sales
91
+ ELSE total_sales / lifespan
92
+ END AS avg_monthly_spend
93
+ FROM customer_aggregation
0 commit comments