Build dbt models to analyze order basket composition, size patterns, and value distribution
harbor run -t snowflake-labs/dbt-basket-composition-analysisharbor download snowflake-labs/dbt-basket-composition-analysisBuild dbt models that analyze order basket composition, including the number of items per order, basket value distribution, customer shopping patterns, half-based trend analysis, and compute composite basket efficiency and growth potential scores.
/app/dbt_transforms (existing project - add your models here)/app/dbt_models_snowflake (existing project - add your models here)basket_analytics (will appear as main_basket_analytics in database)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)DB_TYPE=snowflakeSNOWFLAKE_ACCOUNTSNOWFLAKE_USERSNOWFLAKE_PASSWORDSNOWFLAKE_DATABASE - The clone database to useSNOWFLAKE_SCHEMASNOWFLAKE_WAREHOUSESNOWFLAKE_ROLE (optional)Note: 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 tablesReference source tables using {{ source('enterprise_db', 'TABLE_NAME') }} syntax.
ORDERS.ORDERS via {{ source('enterprise_db', 'ORDERS') }})| Column | Type | Description |
|---|---|---|
| order_id | VARCHAR | Unique order identifier |
| customer_id | VARCHAR | Customer identifier |
| ordered_at | TIMESTAMP | Order timestamp |
| grand_total | DECIMAL | Order total amount |
| status | VARCHAR | Order status (may contain leading/trailing whitespace) |
ORDER_LINES.ORDER_LINES via {{ source('enterprise_db', 'ORDER_LINES') }})| Column | Type | Description |
|---|---|---|
| ORDER_LINE_ID | VARCHAR | Unique line item identifier |
| ORDER_ID | VARCHAR | Reference to orders table |
| PRODUCT_ID | VARCHAR | Product identifier |
| PRODUCT_NAME | VARCHAR | Product name |
| QUANTITY_ORDERED | DECIMAL | Quantity ordered |
| UNIT_PRICE | DECIMAL | Price per unit |
| DISCOUNT_AMOUNT | DECIMAL | Discount applied to line (may be NULL) |
| LINE_TOTAL | DECIMAL | Total amount for line item |
models/staging/stg_order_baskets.sql)Create order-level basket aggregations:
| Column | Type | Description |
|---|---|---|
| order_id | VARCHAR | Order identifier |
| customer_id | VARCHAR | Customer identifier |
| order_date | DATE | Date of the order |
| order_month | INTEGER | Month number (1-12) extracted from order_date |
| order_half | VARCHAR | 'H1' for months 1-6, 'H2' for months 7-12 |
| order_quarter | VARCHAR | 'Q1' for months 1-3, 'Q2' for months 4-6, 'Q3' for months 7-9, 'Q4' for months 10-12 |
| distinct_items | INTEGER | Number of unique products in the basket |
| total_quantity | DECIMAL | Sum of all quantities ordered |
| basket_value | DECIMAL(12,2) | Sum of all line totals |
| total_discount | DECIMAL(12,2) | Sum of all discounts applied (treat NULL as 0) |
| avg_item_price | DECIMAL(10,2) | basket_value / distinct_items |
| max_line_value | DECIMAL(10,2) | Value of the most expensive line item |
| min_line_value | DECIMAL(10,2) | Value of the least expensive line item |
| price_range | DECIMAL(10,2) | Difference between max and min line value |
Filtering rules:
ordered_at >= '2024-01-01' AND ordered_at < '2025-01-01'trim() to the status column before filtering (e.g., trim(status) NOT IN ('CANCELLED', 'RETURNED', 'FAILED'))models/intermediate/int_customer_basket_patterns.sql)Analyze basket patterns at the customer level:
models/intermediate/int_basket_transitions.sql)Track how customers transition between basket size categories over consecutive orders:
| Column | Type | Description |
|---|---|---|
| from_category | VARCHAR | Starting basket size category |
| to_category | VARCHAR | Ending basket size category |
| transition_count | INTEGER | Number of times this transition occurred |
| transition_pct | DECIMAL(5,2) | Percentage of all transitions |
| avg_days_between | DECIMAL(8,2) | Average days between orders for this transition type |
| is_upgrade | BOOLEAN | TRUE if moving to a larger basket size category |
| is_downgrade | BOOLEAN | TRUE if moving to a smaller basket size category |
Transition Logic:
Note: Only include transitions where the customer has at least 2 orders (i.e., at least one transition exists).
| Column | Type | Description |
|---|---|---|
| customer_id | VARCHAR | Customer identifier |
| total_orders | INTEGER | Total number of orders by this customer |
| avg_basket_size | DECIMAL(8,2) | Average distinct items per order |
| avg_basket_value | DECIMAL(10,2) | Average basket value per order |
| total_items_purchased | DECIMAL(10,2) | Sum of total_quantity across all orders |
| total_spent | DECIMAL(12,2) | Sum of basket_value across all orders |
| max_basket_size | INTEGER | Largest number of distinct items in any single order |
| max_basket_value | DECIMAL(10,2) | Highest basket value in any single order |
| single_item_orders | INTEGER | Number of orders with exactly 1 distinct item |
| multi_item_orders | INTEGER | Number of orders with more than 1 distinct item |
| multi_item_ratio | DECIMAL(5,2) | Percentage of orders that are multi-item: (multi_item_orders / total_orders) * 100 |
| avg_price_range | DECIMAL(10,2) | Average price range across all customer orders |
| h1_orders | INTEGER | Number of orders in H1 (months 1-6) |
| h2_orders | INTEGER | Number of orders in H2 (months 7-12) |
| h1_revenue | DECIMAL(12,2) | Total basket_value in H1 |
| h2_revenue | DECIMAL(12,2) | Total basket_value in H2 |
models/marts/basket_size_analysis.sql)Create a table with one row per basket size category containing aggregate metrics, with these columns in exact order (42 columns total):
| # | Column | Type | Description |
|---|---|---|---|
| 1 | basket_size_category | VARCHAR | Size category (see classification rules below) |
| 2 | order_count | INTEGER | Number of orders in this category |
| 3 | total_revenue | DECIMAL(12,2) | Sum of basket_value for all orders in category |
| 4 | avg_basket_value | DECIMAL(10,2) | Average basket value for orders in category |
| 5 | avg_quantity_per_order | DECIMAL(8,2) | Average total quantity per order in category |
| 6 | total_customers | INTEGER | Number of unique customers with orders in this category |
| 7 | avg_discount_per_order | DECIMAL(10,2) | Average discount amount per order |
| 8 | order_share_pct | DECIMAL(5,2) | Percentage of total orders: (category orders / total orders) * 100 |
| 9 | revenue_share_pct | DECIMAL(5,2) | Percentage of total revenue: (category revenue / total revenue) * 100 |
| 10 | customer_share_pct | DECIMAL(5,2) | Percentage of customers who have placed orders in this category |
| 11 | avg_item_price | DECIMAL(10,2) | Average price per item across orders in category |
| 12 | revenue_per_customer | DECIMAL(10,2) | total_revenue / total_customers |
| 13 | size_index | DECIMAL(5,2) | Ratio of revenue share to order share |
| 14 | value_tier | VARCHAR | Value tier based on avg_basket_value (see rules below) |
| 15 | popularity_rank | INTEGER | Rank by order_count (1 = most popular), use dense rank |
| 16 | discount_efficiency | DECIMAL(5,2) | Ratio: total_revenue / (total_discount + 1) |
| 17 | avg_price_range | DECIMAL(10,2) | Average price range across orders in category |
| 18 | h1_order_count | INTEGER | Number of orders in H1 (months 1-6) |
| 19 | h2_order_count | INTEGER | Number of orders in H2 (months 7-12) |
| 20 | h1_revenue | DECIMAL(12,2) | Total revenue in H1 |
| 21 | h2_revenue | DECIMAL(12,2) | Total revenue in H2 |
| 22 | order_growth_rate | DECIMAL(5,2) | Half-over-half order growth: ((h2 - h1) / h1) * 100, NULL if h1 = 0 |
| 23 | revenue_growth_rate | DECIMAL(5,2) | Half-over-half revenue growth: ((h2 - h1) / h1) * 100, NULL if h1 = 0 or NULL |
| 24 | growth_trend | VARCHAR | Trend classification based on order_growth_rate (see rules below) |
| 25 | basket_efficiency_score | INTEGER | Composite efficiency score 5-100 (see calculation below) |
| 26 | growth_potential_score | INTEGER | Composite growth potential score 5-100 (see calculation below) |
| 27 | efficiency_tier | VARCHAR | Efficiency tier based on basket_efficiency_score |
| 28 | growth_tier | VARCHAR | Growth tier based on growth_potential_score |
| 29 | strategic_classification | VARCHAR | Strategic classification combining multiple factors (see rules below) |
| 30 | investment_priority | VARCHAR | Investment priority combining efficiency and growth (see rules below) |
| 31 | quarter_order_volatility | DECIMAL(8,2) | Population standard deviation of order counts across Q1-Q4 |
| 32 | category_momentum | DECIMAL(5,2) | Weighted momentum: (order_growth_rate * 0.4) + (revenue_growth_rate * 0.6), NULL if either is NULL |
| 33 | efficiency_vs_avg | DECIMAL(5,2) | Difference between this category's basket_efficiency_score and the average score across all categories |
| 34 | rank_consistency | INTEGER | Absolute difference between popularity_rank and revenue_rank (where revenue_rank = dense_rank by total_revenue DESC) |
| 35 | avg_customer_orders | DECIMAL(6,2) | Average orders per customer in this category (order_count / total_customers) |
| 36 | relative_discount_rate | DECIMAL(5,2) | This category's avg_discount_per_order as percentage of overall average discount across all categories |
| 37 | composite_score | INTEGER | Combined score: (basket_efficiency_score + growth_potential_score) / 2, rounded to nearest integer |
| 38 | performance_quadrant | VARCHAR | Classification based on efficiency_vs_avg and growth_potential_score (see rules below) |
| 39 | first_order_pct | DECIMAL(5,2) | Percentage of orders in this category that are first-time orders for that customer |
| 40 | repeat_customer_pct | DECIMAL(5,2) | Percentage of customers in this category who have placed 2+ total orders (any category) |
| 41 | upgrade_rate | DECIMAL(5,2) | Percentage of transitions FROM this category that go to a larger category |
| 42 | category_velocity_score | INTEGER | Composite score (0-100) measuring category dynamism (see calculation below) |
Based on distinct_items (number of unique products in the basket):
Based on avg_basket_value for the category:
Based on order_growth_rate (evaluate in order, first match wins):
Measures how much revenue each basket size category generates relative to its order volume:
A composite score combining four weighted components using a tiered point system.
Component 1 - Revenue Contribution (max 30 points): Score based on revenue ranking. Rank categories by revenue_share_pct descending (dense_rank). Award 30 points to rank 1, subtract 10 for each subsequent rank (minimum 0).
Component 2 - Size Index (max 25 points): Tiered scoring based on size_index thresholds:
= 2.0: 25 points
= 1.5: 20 points
= 1.2: 15 points
= 1.0: 10 points
Component 3 - Customer Reach (max 25 points): Tiered scoring based on customer_share_pct thresholds:
= 60%: 25 points
= 40%: 20 points
= 25%: 15 points
= 10%: 10 points
Component 4 - Value Efficiency (max 20 points): Premium = 20, Standard = 12, Economy = 5.
Final Score: Sum all components, bounded between 5 and 100, as INTEGER.
A composite score assessing future growth potential through four components.
Component 1 - Order Growth (max 35 points): Tiered scoring based on order_growth_rate (evaluate in order, first match wins):
> 50%: 35 points> 20% (and <= 50%): 28 points> 0% (and <= 20%): 20 points= 0% (exactly zero): 10 points>= -20% (and < 0%): 5 points< -20%: 0 pointsComponent 2 - Revenue Growth (max 30 points): Same tier structure as order growth (evaluate in order, first match wins):
> 50%: 30 points> 20% (and <= 50%): 24 points> 0% (and <= 20%): 18 points= 0% (exactly zero): 9 points>= -20% (and < 0%): 4 points< -20%: 0 pointsComponent 3 - Market Penetration (max 20 points): INVERSE relationship - untapped markets score higher. Points: <10% -> 20, <25% -> 15, <40% -> 10, <60% -> 5, >=60% -> 2.
Component 4 - Value Headroom (max 15 points): Economy = 15, Standard = 10, Premium = 3.
Final Score: Sum all components, bounded between 5 and 100, as INTEGER.
Based on basket_efficiency_score:
Based on growth_potential_score:
Combine value_tier and customer_share_pct to determine strategic priority. Evaluate conditions in the order shown below (first match wins):
Combine efficiency_tier and growth_tier to determine where to invest. Evaluate conditions in the order shown below (first match wins):
Calculate the population standard deviation of order counts across the four quarters (Q1, Q2, Q3, Q4) for each basket size category. Round to 2 decimal places.
A weighted combination of growth rates:
Calculate how each category's efficiency score compares to the average:
Measures how consistently a category ranks by volume vs. revenue:
Simple ratio of order_count to total_customers for each category. Round to 2 decimal places.
Compare this category's discounting to the overall average:
Simple average of the two main scores:
Classify categories into quadrants based on efficiency relative to average AND growth potential:
For each basket size category, calculate what percentage of orders are first-time orders:
For each basket size category, calculate what percentage of customers are repeat customers:
Using data from int_basket_transitions, calculate the upgrade rate for each category:
from_category equals this categoryis_upgrade = TRUEA composite score measuring how dynamic/active a category is, combining:
Component 1 - Transition Activity (max 40 points):
Component 2 - First-Time Buyer Attraction (max 30 points):
= 40%: 30 points
= 25%: 20 points
= 10%: 10 points
Component 3 - Customer Retention (max 30 points):
= 70%: 30 points
= 50%: 22 points
= 30%: 15 points
Final Score: Sum all components, cast as INTEGER. Score naturally bounded 0-100.
models/intermediate/int_customer_cohorts.sql)Analyze customer behavior based on their FIRST basket size category (cohort). Each customer belongs to exactly one cohort based on their first order in 2024.
| Column | Type | Description |
|---|---|---|
| cohort_category | VARCHAR | The basket size category of the customer's FIRST order |
| cohort_size | INTEGER | Number of customers whose first order was in this category |
| total_cohort_orders | INTEGER | Total orders placed by customers in this cohort (including first order) |
| total_cohort_revenue | DECIMAL(12,2) | Total revenue from customers in this cohort |
| avg_orders_per_customer | DECIMAL(6,2) | Average orders per customer in cohort |
| repeat_rate | DECIMAL(5,2) | Percentage of cohort customers who placed 2+ orders |
| upgrade_rate | DECIMAL(5,2) | Percentage of cohort's non-first orders that were in a LARGER category than their first |
| downgrade_rate | DECIMAL(5,2) | Percentage of cohort's non-first orders that were in a SMALLER category than their first |
| same_category_rate | DECIMAL(5,2) | Percentage of cohort's non-first orders that were in the SAME category as their first |
| cohort_share_pct | DECIMAL(5,2) | Percentage of total customers in this cohort |
Calculation Notes:
models/marts/transition_summary.sql)Create a table summarizing basket size transitions with these columns in exact order (8 columns total):
| # | Column | Type | Description |
|---|---|---|---|
| 1 | category | VARCHAR | Basket size category |
| 2 | total_incoming_transitions | INTEGER | Total transitions TO this category from other categories |
| 3 | total_outgoing_transitions | INTEGER | Total transitions FROM this category to other categories |
| 4 | net_transition_flow | INTEGER | incoming - outgoing (positive = net gain, negative = net loss) |
| 5 | retention_transitions | INTEGER | Transitions where from_category = to_category = this category |
| 6 | inflow_rate | DECIMAL(5,2) | Percentage of all transitions that flow INTO this category |
| 7 | outflow_rate | DECIMAL(5,2) | Percentage of all transitions that flow OUT OF this category |
| 8 | transition_balance | VARCHAR | 'Net Gainer' if net_transition_flow > 0, 'Net Loser' if < 0, 'Balanced' if = 0 |
Calculation Notes:
Note: If your models appear in a different schema than expected, re-check your work and review how dbt handles schema naming when a custom schema is specified.
{% if target.type == 'snowflake' %}) for DuckDB-specific vs Snowflake-specific syntax