SQL Dojo
Metric

Metric types: simple, ratio, derived, cumulative, conversion

The five metric types a semantic layer such as dbt's MetricFlow knows, and the SQL each one compiles to: what to sum, what to divide, and when.

A semantic layer stores each metric once and writes the SQL of every request. dbt's MetricFlow names five types, each with a familiar SQL shape:

  • simple: one aggregate, with its filter: SUM(quantity * unit_price) of the orders not cancelled.
  • ratio: one metric over another, each summed at the grain asked, then divided: SUM(failed) / SUM(payments), never AVG(failure_pct).
  • derived: an expression of metrics (revenue / active_customers, the change on last month): each input is aggregated on its own, then joined on the dimensions.
  • cumulative: a running or trailing total, or a period to date: SUM(revenue) OVER (ORDER BY month).
  • conversion: the share of base events (a pricing view) followed by a conversion event (a subscription) of the same user within a window.

A derived metric compiles like this:

SELECT r.month, r.revenue / a.active_customers AS revenue_per_active_customer
FROM (SELECT month, SUM(amount) AS revenue
      FROM sales WHERE status <> 'cancelled' GROUP BY month) r
JOIN (SELECT month, COUNT(DISTINCT customer_id) AS active_customers
      FROM orders GROUP BY month) a
  ON a.month = r.month;

The trap. Computing two inputs in one pass over joined rows: a filter written for one leaks into the other, and a join repeats rows of one of them. Aggregate each input with its own filter and grain, then combine. Other layers (Snowflake semantic views, Databricks metric views) define metrics in their own syntax, not always with these names.

-- simple: revenue; ratio: revenue / orders; derived: revenue / active customers (orders of every status);
-- cumulative: revenue since January
WITH sales AS (
  SELECT CAST(DATE_TRUNC('month', o.ordered_at) AS DATE) AS month,
         SUM(l.quantity * l.unit_price) AS revenue,
         COUNT(DISTINCT o.order_id) AS orders
  FROM orders o
  JOIN order_lines l ON l.order_id = o.order_id
  WHERE o.status <> 'cancelled'
  GROUP BY 1
),
active AS (
  SELECT CAST(DATE_TRUNC('month', ordered_at) AS DATE) AS month,
         COUNT(DISTINCT customer_id) AS active_customers
  FROM orders
  GROUP BY 1
)
SELECT s.month,
       s.revenue,
       ROUND(s.revenue / s.orders, 2) AS average_basket,
       ROUND(s.revenue / a.active_customers, 2) AS revenue_per_customer,
       SUM(s.revenue) OVER (ORDER BY s.month) AS revenue_ytd
FROM sales s
JOIN active a ON a.month = s.month
WHERE s.month >= DATE '2025-01-01' AND s.month < DATE '2025-07-01'
ORDER BY s.month;
monthrevenueaverage_basketrevenue_per_customerrevenue_ytd
2025-01-015656.0062.8478.565656.00
2025-02-015015.5059.7167.7810671.50
2025-03-016665.6075.7581.2917337.10
2025-04-016534.1065.3479.6823871.20
2025-05-016146.8063.3768.330018.00
2025-06-016316.2067.9277.0336334.20
Try it in Randori