Build dbt models to analyze time intervals between consecutive customer orders and classify ordering patterns
harbor run -t snowflake-labs/dbt-order-interval-metricsharbor download snowflake-labs/dbt-order-interval-metricsBuild dbt models that analyze the time intervals between consecutive customer orders to understand purchasing patterns, classify customers by their ordering frequency, assess customer value and churn risk, track behavioral momentum, and predict customer lifecycle stages.
This task supports both DuckDB and Snowflake. Run echo $DB_TYPE in a shell BEFORE you write any code or spawn any subagents — the live env determines which backend the verifier runs against. Do NOT assume a default from this prose. Both /app/dbt_models_duckdb/ and /app/dbt_models_snowflake/ exist on disk; the verifier only checks the project matching the live $DB_TYPE.
DB_TYPE=duckdb$DUCKDB_PATH (default: /app/database/retail.duckdb)/app/dbt_models_duckdbDB_TYPE=snowflakeSNOWFLAKE_ACCOUNTSNOWFLAKE_USERSNOWFLAKE_PASSWORDSNOWFLAKE_DATABASE - The clone database to useSNOWFLAKE_SCHEMASNOWFLAKE_WAREHOUSESNOWFLAKE_ROLE (optional)/app/dbt_models_snowflakeNote: For Snowflake, the entrypoint automatically creates a clone database and sets SNOWFLAKE_DATABASE. The clone is destroyed when the task completes.
You must configure dbt to connect to the database:
profiles.yml in the dbt project directory with profile name retail_dw_masterDBT_PROFILES_DIR environment variable to the directory containing profiles.ymlConfigure with type: duckdb and the database path from $DUCKDB_PATH.
Configure with type: snowflake using password authentication:
You will add models to the existing dbt project. The project is already configured with:
enterprise_db schemaImportant:
dbt deps before dbt run to install dependencies{{ source('enterprise_db', 'TABLE_NAME') }} syntax to reference source tablesorder_analytics (will appear as main_order_analytics in DuckDB, or default schema in Snowflake)Snowflake schema routing: On Snowflake, models must land in the main schema (the default schema of the clone database). To achieve this, override the generate_schema_name macro so that dbt places all models in the target schema defined in profiles.yml, ignoring any custom schema config. Create macros/generate_schema_name.sql (or overwrite the existing one if present) with a macro that returns the default schema unconditionally. Set the Snowflake profile's schema to main.
Reference source tables using {{ source('enterprise_db', 'TABLE_NAME') }} syntax.
{{ source('enterprise_db', 'ORDERS') }})Contains order data including order_id, customer_id, ordered_at, grand_total, and status columns. Explore the table to understand available columns and data types.
models/staging/stg_orders__timeline.sql)ordered_at >= '2024-01-01' AND ordered_at < '2025-01-01'models/intermediate/int_customer_order_gaps.sql)Calculate the time gap between consecutive orders for each customer:
| Column | Type | Description |
|---|---|---|
| customer_id | VARCHAR | Customer identifier |
| order_date | DATE | Date of the order |
| grand_total | DECIMAL | Order amount |
| order_sequence | INTEGER | Sequential order number for this customer (1, 2, 3...) |
| prev_order_date | DATE | Date of customer's previous order (NULL for first order) |
| days_since_prev_order | INTEGER | Days between this order and previous order (NULL for first order) |
| order_half | VARCHAR | 'first_half' or 'second_half' - which half of customer's orders this belongs to |
Important: Order sequence must be based on order_date ascending for each customer. For tie-breaking, use order_id ascending.
models/marts/customer_order_intervals.sql)Create a table with one row per customer containing interval metrics, with these columns in exact order:
| Column | Type | Description |
|---|---|---|
| customer_id | VARCHAR | Customer identifier |
| total_orders | INTEGER | Total number of orders by this customer |
| first_order_date | DATE | Date of customer's first order |
| last_order_date | DATE | Date of customer's most recent order |
| customer_lifespan_days | INTEGER | Days between first and last order (0 if only 1 order) |
| total_revenue | DECIMAL(12,2) | Sum of all order amounts |
| avg_order_value | DECIMAL(12,2) | total_revenue / total_orders |
| avg_days_between_orders | DECIMAL(8,2) | Average days between consecutive orders (NULL if only 1 order) |
| min_days_between_orders | INTEGER | Minimum gap between orders (NULL if only 1 order) |
| max_days_between_orders | INTEGER | Maximum gap between orders (NULL if only 1 order) |
| std_dev_days | DECIMAL(8,2) | Standard deviation of order intervals (NULL if fewer than 3 orders) |
| ordering_frequency | VARCHAR | Frequency classification (see rules below) |
| is_repeat_customer | VARCHAR(1) | 'Y' if total_orders > 1, 'N' otherwise |
| days_since_last_order | INTEGER | Days from last_order_date to reference date (2024-12-31) |
| customer_tier | VARCHAR | Value tier based on revenue quartiles (see rules below) |
| churn_risk | VARCHAR | Churn risk assessment (see rules below) |
| purchase_consistency | VARCHAR | Ordering pattern consistency (see rules below) |
| customer_value_score | INTEGER | Composite value score 0-100 (see calculation below) |
| customer_segment | VARCHAR | Customer segment based on value score (see rules below) |
| order_acceleration | VARCHAR | Whether ordering frequency is accelerating or decelerating (see rules below) |
| monthly_order_rate | DECIMAL(8,2) | Orders per month of active period (see calculation below) |
| spending_trend | VARCHAR | Whether spending per order is trending up or down (see rules below) |
| loyalty_index | INTEGER | Composite loyalty score 0-100 (see calculation below) |
| engagement_momentum | VARCHAR | Behavioral trajectory classification (see rules below) |
| lifecycle_stage | VARCHAR | Customer lifecycle stage classification (see rules below) |
Based on avg_days_between_orders:
Divide customers into four equal-sized groups (quartiles) by total_revenue:
Based on days_since_last_order and total_orders:
Important: Evaluate the conditions in order - a customer with days_since >= 120 should be 'High' regardless of total_orders.
Based on coefficient of variation (CV) of order intervals (std_dev / mean):
A composite RFM-style score combining three components:
Revenue Component (0-40 points): Based on customer's percentile position in revenue distribution
Frequency Component (0-30 points): Based on ordering_frequency classification
Recency Component (0-30 points): Linear decay over one year
Final Score: Sum of all three components as an integer (minimum 5, maximum 100)
Based on customer_value_score:
Compare average days between orders in the first half of a customer's orders to the second half:
Note: For customers with odd number of orders, the middle order goes to the first half.
Calculate orders per month based on active period:
Compare average order value in the first half of orders to the second half:
A composite score measuring customer loyalty:
Tenure Component (0-30 points): Based on customer_lifespan_days
Repeat Purchase Component (0-40 points): Based on total_orders
Consistency Component (0-30 points): Based on purchase_consistency
Final Score: Sum of all three components as an integer (minimum 0, maximum 100)
Combine order_acceleration and spending_trend to determine behavioral trajectory:
Note: Evaluate 'Inactive' first (highest priority), then 'Emerging', then the acceleration/deceleration logic.
Based on combination of total_orders, days_since_last_order, and customer_lifespan_days. Evaluate conditions in this order (first match wins):
Important: 'Churned' takes highest priority -- a customer with days_since_last_order >= 120 is always 'Churned' regardless of other conditions.