Skip to content

3. Customer Order Summary Mart

Difficulty: Medium · Topic: Refs & marts

Build the customers mart from two staging models, {{ ref('stg_customers') }} and {{ ref('stg_orders') }}. One row per customer, including customers who have never ordered:

Returned orders (status = 'returned') do not count anywhere: not in the dates, the count or the value.

Your model is compiled like dbt does and run in DuckDB against 3 test cases, including hidden edge cases.

Sample inputs

{{ ref('stg_customers') }}

customer_idfirst_namelast_name
1AnaSilva
2BoChen
3CyOkafor

{{ ref('stg_orders') }}

order_idcustomer_idordered_onstatusamount
10012024-01-03completed20
10112024-02-10completed35.5
10222024-01-15shipped12.25
10322024-03-01returned99

Expected output

customer_idfull_namefirst_order_onmost_recent_order_onnumber_of_orderslifetime_value
1Ana Silva2024-01-032024-02-10255.5
2Bo Chen2024-01-152024-01-15112.25
3Cy Okafornullnull00

Hints

Hint 1Aggregate orders per customer in a CTE first, then left join it to customers. Joining first and aggregating after works too, but is easier to get wrong.
Hint 2Filter returned orders inside the orders CTE. A where status != 'returned' after a left join removes customers whose only orders were returned.
Hint 3After a left join, missing aggregates are null: coalesce(..., 0) turns them into 0. And count(*) would count the null row as 1.

More dbt problems

All dbt problems