队列分析(Cohort)

SQL查询入门SQL

问题

创建用户队列分析表:按首次购买月份分组,追踪各队列后续每月的复购率。

答题要点

WITH first_purchase AS (
    SELECT
        customer_id,
        DATE_FORMAT(MIN(order_date), '%Y-%m') AS cohort_month
    FROM orders
    GROUP BY customer_id
),
cohort_data AS (
    SELECT
        fp.cohort_month,
        TIMESTAMPDIFF(MONTH, STR_TO_DATE(CONCAT(fp.cohort_month, '-01'), '%Y-%m-%d'),
                      DATE_FORMAT(o.order_date, '%Y-%m-01')) AS month_number,
        COUNT(DISTINCT o.customer_id) AS customers
    FROM first_purchase fp
    JOIN orders o ON fp.customer_id = o.customer_id
    GROUP BY fp.cohort_month, month_number
)
SELECT
    cohort_month,
    MAX(CASE WHEN month_number = 0 THEN customers END) AS month_0,
    MAX(CASE WHEN month_number = 1 THEN customers END) AS month_1,
    MAX(CASE WHEN month_number = 2 THEN customers END) AS month_2,
    MAX(CASE WHEN month_number = 3 THEN customers END) AS month_3
FROM cohort_data
GROUP BY cohort_month
ORDER BY cohort_month;

完整解析在题库里看

核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。

去练这道题

回知识库看这一块

同一能力的其他题