DSP-025Product DSSQL

算 CRR(customer retention rate),但附加条件非常多;需要 4–5 个 CTE,且用到 LAG

📋 题目详细背景与场景

概括一下是要算CRR 但是有非常多的附加条件 本来想用cte+join做 但是牵扯太多没做出来

💡 官方参考解答与考察要点

考官评估核心: 复杂条件下的客户留存率(CRR)计算要求拆解为 4–5 个职责单一的 CTE:定义 Cohort 与有效留存条件、去重状态序列、利用 `LAG()` 识别连续周期状态迁移,最终安全求率。
  • Clarifying Questions:逐条确认 CRR 附加条件——什么算有效客户(如最低消费/非试用/未退款)、留存周期窗口(月度还是季度)、流失后回流(Resurrected)是否计入留存,以及分母是期初总活跃数还是特定 Cohort。
  • 核心 SQL 逻辑:采用模块化 CTE 管线:`valid_events` 过滤退款与测试单 -> `monthly_active` 规范化用户-月粒度 -> `with_prev_month` 用 `LAG(month_idx)` 与 `DATE_DIFF` 判断是否为连续留存 -> `cohort_summary` 聚合分子分母并使用 `NULLIF` 计算 CRR。
  • Edge Cases & Red Flags:试图在一个巨型 `JOIN` 中同时做日期对齐、退款剔除和多周期比较极易导致行膨胀和逻辑错乱;`LAG()` 必须基于用户级去重后的周期表,否则同一月多次购买会错判间隔。
  • 常见 Follow-up:如果业务规定“宽限期 1 个月”(允许跳过单月但第 3 个月活跃仍算留存),`LAG` 和 `DATE_DIFF` 条件该如何调整?如何进一步拆解 NRR(Net Revenue Retention)?
WITH valid_orders AS (
  SELECT DISTINCT
    customer_id,
    DATE_TRUNC(order_date, MONTH) AS active_month
  FROM orders
  WHERE order_status = 'completed'
    AND is_trial = FALSE
    AND net_amount > 0
),
customer_tenure AS (
  SELECT
    customer_id,
    active_month,
    MIN(active_month) OVER (PARTITION BY customer_id) AS cohort_month,
    LAG(active_month) OVER (PARTITION BY customer_id ORDER BY active_month) AS prev_active_month
  FROM valid_orders
),
classified AS (
  SELECT
    active_month,
    cohort_month,
    customer_id,
    CASE
      WHEN DATE_DIFF(active_month, prev_active_month, MONTH) = 1 THEN 1
      ELSE 0
    END AS is_retained_from_prev
  FROM customer_tenure
),
monthly_agg AS (
  SELECT
    active_month,
    COUNT(DISTINCT customer_id) AS active_customers,
    SUM(is_retained_from_prev) AS retained_customers
  FROM classified
  GROUP BY active_month
)
SELECT
  active_month,
  active_customers,
  LAG(active_customers) OVER (ORDER BY active_month) AS prev_month_customers,
  retained_customers,
  ROUND(
    retained_customers * 1.0 / NULLIF(LAG(active_customers) OVER (ORDER BY active_month), 0),
    4
  ) AS crr
FROM monthly_agg
ORDER BY active_month;

📖 对应核心知识点手册:

想用苏格拉底式对话深入理解该考点的第一性原理?

进入破冰推演实验室,模拟考官互动并一步步拆解底层机制与直觉陷阱。

💬 针对本考点破冰 ➔
⚡
想检验本题的肌肉记忆?进入 3 阶闪卡主动回忆盲测
隐藏答案遮罩,自测:审题锚点 ➔ 数理公式机理 ➔ 工业标杆代码与连环追问。3 分钟攻破认知盲区!
🎯 立即在闪卡中盲测此题➔