← 中文资源

简体中文版本

用 CTE 搭留存矩阵

先按首次活跃月份给用户归组,再 JOIN 后续活跃月份计算 months_since,最后用条件聚合成留存矩阵;每月一列,流失一眼可见。

阅读英文原文

实现说明

这个文件依次执行 SELECT / INSERT / CREATE 语句,涉及 events、a.active_month、c.cohort_month、cohorts、activity。 events 是本文件运行时创建的会话级临时表——不用先建表,会话收尾时一并回收。 把语句拆开看,工作部件是:先用 WITH … AS 把中间结果命名成 CTE,主查询再引用它;通过 一个 JOIN 把几张表的行按条件接到一起;WHERE 决定这条语句会作用到哪些行;用 COUNT、MIN 做聚合;GROUP BY 把同组行折叠成每个分组一行;ORDER BY 固定了输出顺序;DISTINCT 折叠重复行;必填列上的 NOT NULL 限定。

常见问题

这段 SQL 涉及哪些关系?

events、a.active_month、c.cohort_month、cohorts、activity——经一个 JOIN 子句连接。

核心语句

INSERT INTO events (user_id, occurred_at) VALUES
    (1, '2026-07-03'), (1, '2026-07-20'), (1, '2026-09-02'),
    (2, '2026-07-11'), (2, '2026-08-01'),
    (3, '2026-08-15'), (3, '2026-08-30');
CREATE TEMP TABLE events (
    user_id     integer NOT NULL,
    occurred_at date    NOT NULL
);

代码示例

-- retention matrix: cohort users by their first active month, then track how many stay active in each later month
CREATE TEMP TABLE events (
    user_id     integer NOT NULL,
    occurred_at date    NOT NULL
);

INSERT INTO events (user_id, occurred_at) VALUES
    (1, '2026-07-03'), (1, '2026-07-20'), (1, '2026-09-02'),
    (2, '2026-07-11'), (2, '2026-08-01'),
    (3, '2026-08-15'), (3, '2026-08-30');

WITH cohorts AS (
    -- first active month assigns the cohort
    SELECT user_id,
           date_trunc('month', min(occurred_at))::date AS cohort_month
    FROM events
    GROUP BY user_id
),
activity AS (
    -- every month each user was active (deduplicated)
    SELECT DISTINCT user_id,
           date_trunc('month', occurred_at)::date AS active_month
    FROM events
),
months AS (
    SELECT
        c.cohort_month,
        (extract(year FROM a.active_month) - extract(year FROM c.cohort_month)) * 12
            + extract(month FROM a.active_month)
            - extract(month FROM c.cohort_month) AS months_since,
        count(DISTINCT a.user_id) AS active_users
    FROM cohorts c
    JOIN activity a USING (user_id)
    GROUP BY c.cohort_month, months_since
)
SELECT
    cohort_month,
    count(*) FILTER (WHERE months_since = 0) AS size_m0,
    count(*) FILTER (WHERE months_since = 1) AS m1,
    count(*) FILTER (WHERE months_since = 2) AS m2
FROM months
GROUP BY cohort_month
ORDER BY cohort_month;