dbt: How to implement a ratio metric


✅ The Concept: Ratio Metric in dbt

In dbt’s metrics layer (enabled via dbt Metrics), a ratio metric is used to calculate things like:

  • Conversion rate = conversions / sessions
  • Return rate = returned orders / total orders
  • Average order value = revenue / number of orders

To implement this, dbt requires that:

  1. The numerator metric is already defined
  2. The denominator metric is already defined
  3. The ratio metric references them

📦 Example Use Case: Conversion Rate

We want to define a conversion_rate metric based on:

  • Numerator: conversions
  • Denominator: sessions

🔹 Step 1: Define the conversions Metric

metrics:
  - name: conversions
    label: Total Conversions
    model: ref('fct_events')
    description: Number of successful purchases
    calculation_method: count
    expression: event_id
    filter: event_type = 'purchase'
    time_grains: [day, week, month]

🔹 Step 2: Define the sessions Metric

  - name: sessions
    label: Total Sessions
    model: ref('fct_events')
    description: Number of user sessions
    calculation_method: count
    expression: session_id
    filter: event_type = 'session_start'
    time_grains: [day, week, month]

🔹 Step 3: Define the conversion_rate Ratio Metric

  - name: conversion_rate
    label: Conversion Rate
    description: Percentage of sessions that result in a purchase
    calculation_method: ratio
    numerator: conversions
    denominator: sessions
    time_grains: [day, week, month]
    format: percentage

✅ dbt will compute:
conversion_rate = count(purchase events) / count(session_start events)


🧠 Optional Enhancements

You can also add:

  • dimensions: to slice the ratio by region, device type, etc.
  • window: to compute rolling averages
    dimensions: [device_type, country]
    window: 7 days

✅ Summary

Metric NameTypeNotes
conversionsBaseDefined using calculation_method: count
sessionsBaseAnother base metric
conversion_rateRatioUses numerator + denominator

📌 Why It’s Required

dbt needs both base metrics explicitly defined, so it knows:

  • How to aggregate them
  • At what time grain
  • What filters to apply
  • How to recompute them if logic changes

Leave a Reply

Your email address will not be published. Required fields are marked *