-
Notifications
You must be signed in to change notification settings - Fork 380
Expand file tree
/
Copy pathcustomer_revenue_by_day.sql
More file actions
47 lines (46 loc) · 1.11 KB
/
customer_revenue_by_day.sql
File metadata and controls
47 lines (46 loc) · 1.11 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
{{
config(
materialized='incremental',
incremental_strategy='incremental_by_time_range',
cluster_by=['ds'],
time_column='ds',
)
}}
WITH order_total AS (
SELECT
oi.order_id AS order_id,
SUM(oi.quantity * i.price) AS total,
oi.ds AS ds
FROM {{ ref('order_items') }} AS oi
LEFT JOIN {{ ref('items') }} AS i
ON oi.item_id = i.id AND oi.ds = i.ds
{% if is_incremental() %}
WHERE
oi.ds > (select max(ds) from {{ this }})
{% endif %}
{% if sqlmesh_incremental is defined %}
WHERE
oi.ds BETWEEN '{{ start_ds }}' AND '{{ end_ds }}'
{% endif %}
GROUP BY
oi.order_id,
oi.ds
)
SELECT
o.customer_id::INT AS customer_id, /* Customer id */
SUM(ot.total)::DOUBLE AS revenue, /* Revenue from orders made by this customer */
o.ds::TEXT AS ds /* Date */
FROM {{ ref('orders') }} AS o
LEFT JOIN order_total AS ot
ON o.id = ot.order_id AND o.ds = ot.ds
{% if is_incremental() %}
WHERE
o.ds > (select max(ds) from {{ this }})
{% endif %}
{% if sqlmesh_incremental is defined %}
WHERE
o.ds BETWEEN '{{ start_ds }}' AND '{{ end_ds }}'
{% endif %}
GROUP BY
o.customer_id,
o.ds