-
Notifications
You must be signed in to change notification settings - Fork 182
/
Copy pathcustomers.sql
58 lines (38 loc) · 1.24 KB
/
customers.sql
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
with
customers as (
select * from {{ ref('stg_customers') }}
),
orders as (
select * from {{ ref('orders') }}
),
customer_orders_summary as (
select
orders.customer_id,
count(distinct orders.order_id) as count_lifetime_orders,
count(distinct orders.order_id) > 1 as is_repeat_buyer,
min(orders.ordered_at) as first_ordered_at,
max(orders.ordered_at) as last_ordered_at,
sum(orders.subtotal) as lifetime_spend_pretax,
sum(orders.tax_paid) as lifetime_tax_paid,
sum(orders.order_total) as lifetime_spend
from orders
group by 1
),
joined as (
select
customers.*,
customer_orders_summary.count_lifetime_orders,
customer_orders_summary.first_ordered_at,
customer_orders_summary.last_ordered_at,
customer_orders_summary.lifetime_spend_pretax,
customer_orders_summary.lifetime_tax_paid,
customer_orders_summary.lifetime_spend,
case
when customer_orders_summary.is_repeat_buyer then 'returning'
else 'new'
end as customer_type
from customers
left join customer_orders_summary
on customers.customer_id = customer_orders_summary.customer_id
)
select * from joined