SQL Dojo
Indicador

Retención por cohortes en SQL

Agrupar a los clientes por el mes de su primer pedido y medir qué parte sigue activa 1, 2 y 3 meses después, dejando vacías las cohortes demasiado jóvenes.

¿Siguen volviendo los clientes que captamos? Agrúpelos en cohortes según el mes de su primer pedido; la retención en el mes N es la proporción de una cohorte que está activa (aquí: vuelve a pedir) N meses después de su primer mes.

WITH firsts AS (
  SELECT customer_id,
         DATE_TRUNC('month', ordered_at) AS order_month,
         MIN(DATE_TRUNC('month', ordered_at)) OVER (PARTITION BY customer_id) AS cohort
  FROM orders
  WHERE status <> 'cancelled'
),
aged AS (
  SELECT customer_id, cohort,
         (EXTRACT(YEAR FROM order_month) - EXTRACT(YEAR FROM cohort)) * 12
           + EXTRACT(MONTH FROM order_month) - EXTRACT(MONTH FROM cohort) AS age
  FROM firsts
)
SELECT cohort,
       COUNT(DISTINCT customer_id) AS customers,
       COUNT(DISTINCT CASE WHEN age = 1 THEN customer_id END) AS active_m1
FROM aged
GROUP BY cohort
ORDER BY cohort;

Añade una columna por antigüedad y divídela entre customers para obtener la tasa. Lee la matriz por columnas para comparar cohortes, y por diagonales para ver el efecto del calendario: una temporada afecta a todas las cohortes en el mismo mes.

La trampa. Una cohorte demasiado reciente para haber llegado al mes N muestra un 0 %, y el gráfico parece un desplome: deja la celda vacía, CASE WHEN ese mes haya terminado THEN … END, sin ELSE. Y determine el primer mes sobre todo el historial antes de filtrar las cohortes que muestra: si filtra antes los pedidos, cualquier cliente antiguo parece nuevo.

En tu almacén de datos. En BigQuery se escribe DATE_TRUNC(DATE(ordered_at), MONTH). La antigüedad en meses se calcula de forma más corta con DATEDIFF(month, cohort, order_month) en Snowflake y DATE_DIFF(order_month, cohort, MONTH) en BigQuery.

-- The data stops on 27 December 2025: a cell counts only if its month ended before December.
WITH firsts AS (
  SELECT customer_id,
         CAST(DATE_TRUNC('month', ordered_at) AS DATE) AS order_month,
         CAST(MIN(DATE_TRUNC('month', ordered_at)) OVER (PARTITION BY customer_id) AS DATE) AS cohort
  FROM orders
  WHERE status <> 'cancelled'
)
SELECT cohort,
       COUNT(DISTINCT customer_id) AS customers,
       CASE WHEN cohort + INTERVAL 1 MONTH < DATE '2025-12-01'
            THEN ROUND(100.0 * COUNT(DISTINCT CASE WHEN order_month = cohort + INTERVAL 1 MONTH THEN customer_id END)
                       / COUNT(DISTINCT customer_id), 1) END AS m1_pct,
       CASE WHEN cohort + INTERVAL 2 MONTH < DATE '2025-12-01'
            THEN ROUND(100.0 * COUNT(DISTINCT CASE WHEN order_month = cohort + INTERVAL 2 MONTH THEN customer_id END)
                       / COUNT(DISTINCT customer_id), 1) END AS m2_pct,
       CASE WHEN cohort + INTERVAL 3 MONTH < DATE '2025-12-01'
            THEN ROUND(100.0 * COUNT(DISTINCT CASE WHEN order_month = cohort + INTERVAL 3 MONTH THEN customer_id END)
                       / COUNT(DISTINCT customer_id), 1) END AS m3_pct
FROM firsts
WHERE cohort >= DATE '2025-06-01'
GROUP BY cohort
ORDER BY cohort;
cohortcustomersm1_pctm2_pctm3_pct
2025-06-01540.040.020.0
2025-07-011145.527.336.4
2025-08-01742.928.642.9
2025-09-011323.130.8NULL
2025-10-011145.5NULLNULL
2025-11-0114NULLNULLNULL
2025-12-013NULLNULLNULL
Probarlo en Randori