Repository navigation
Expand file tree
/
Copy pathproject question 3.sql
More file actions
49 lines (42 loc) · 1.65 KB
/
Copy pathproject question 3.sql
File metadata and controls
49 lines (42 loc) · 1.65 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
WITH
payment_with_year_month_table AS (
SELECT *,
CAST(SUBSTR(paymentDate, 1,4) AS INTEGER)*100 + CAST(SUBSTR(paymentDate, 6,7) AS INTEGER) AS year_month
FROM payments p
),
customers_by_month_table AS (
SELECT p1.year_month, COUNT(*) AS number_of_customers, SUM(p1.amount) AS total
FROM payment_with_year_month_table p1
GROUP BY p1.year_month
),
new_customers_by_month_table AS (
SELECT p1.year_month,
COUNT(*) AS number_of_new_customers,
SUM(p1.amount) AS new_customer_total,
(SELECT number_of_customers
FROM customers_by_month_table c
WHERE c.year_month = p1.year_month) AS number_of_customers,
(SELECT total
FROM customers_by_month_table c
WHERE c.year_month = p1.year_month) AS total
FROM payment_with_year_month_table p1
WHERE p1.customerNumber NOT IN (SELECT customerNumber
FROM payment_with_year_month_table p2
WHERE p2.year_month < p1.year_month)
GROUP BY p1.year_month
)
SELECT year_month,
ROUND(number_of_new_customers*100/number_of_customers,1) AS number_of_new_customers_props,
ROUND(new_customer_total*100/total,1) AS new_customers_total_props
FROM new_customers_by_month_table;
----- the average of the profit from each customer
WITH profit_cte as
(SELECT o.customerNumber,
(sum(od.quantityOrdered * (od.priceEach - p.buyPrice)))
as profit_per_customer
FROM products p
JOIN orderdetails od on p.productCode = od.productCode
JOIN orders o on od.orderNumber = o.orderNumber
GROUP by o.customerNumber)
SELECT round(avg(pcte.profit_per_customer), 2) as Customer_Lifetime_Value
FROM profit_cte pcte;