Skip to content

Commit 70151fe

Browse files
even-weiwcchang1115
authored andcommitted
Convert CTEs in customers into intermediate models
Signed-off-by: Even Wei <[email protected]>
1 parent e525ec3 commit 70151fe

File tree

3 files changed

+35
-69
lines changed

3 files changed

+35
-69
lines changed

models/customers.sql

+16-69
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,16 @@
1-
with customers as (
2-
3-
select * from {{ ref('stg_customers') }}
4-
5-
),
6-
7-
orders as (
8-
9-
select * from {{ ref('stg_orders') }}
10-
11-
),
12-
13-
payments as (
14-
15-
select * from {{ ref('stg_payments') }}
16-
17-
),
18-
19-
customer_orders as (
20-
21-
select
22-
customer_id,
23-
24-
min(order_date) as first_order,
25-
max(order_date) as most_recent_order,
26-
count(order_id) as number_of_orders
27-
from orders
28-
29-
group by customer_id
30-
31-
),
32-
33-
customer_payments as (
34-
35-
select
36-
orders.customer_id,
37-
sum(amount)::bigint as total_amount
38-
39-
from payments
40-
41-
left join orders on
42-
payments.order_id = orders.order_id
43-
44-
group by orders.customer_id
45-
46-
),
47-
48-
final as (
49-
50-
select
51-
customers.customer_id,
52-
customers.first_name,
53-
customers.last_name,
54-
customer_orders.first_order,
55-
customer_orders.most_recent_order,
56-
customer_orders.number_of_orders,
57-
customer_payments.total_amount as customer_lifetime_value
58-
59-
from customers
60-
61-
left join customer_orders
62-
on customers.customer_id = customer_orders.customer_id
63-
64-
left join customer_payments
65-
on customers.customer_id = customer_payments.customer_id
66-
67-
)
68-
69-
select * from final
1+
select
2+
customers.customer_id,
3+
customers.first_name,
4+
customers.last_name,
5+
customer_orders.first_order,
6+
customer_orders.most_recent_order,
7+
customer_orders.number_of_orders,
8+
customer_payments.total_amount as customer_lifetime_value
9+
10+
from {{ ref('stg_customers') }} customers
11+
12+
left join {{ ref('int_customer_orders') }} customer_orders
13+
on customers.customer_id = customer_orders.customer_id
14+
15+
left join {{ ref('int_customer_payments') }} customer_payments
16+
on customers.customer_id = customer_payments.customer_id

models/int_customer_orders.sql

+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
select
2+
customer_id,
3+
4+
min(order_date) as first_order,
5+
max(order_date) as most_recent_order,
6+
count(order_id) as number_of_orders
7+
from {{ ref('stg_orders') }}
8+
9+
group by customer_id

models/int_customer_payments.sql

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
select
2+
orders.customer_id,
3+
sum(amount)::bigint as total_amount
4+
5+
from {{ ref('stg_payments') }} payments
6+
7+
left join {{ ref('stg_orders') }} orders on
8+
payments.order_id = orders.order_id
9+
10+
group by orders.customer_id

0 commit comments

Comments
 (0)