归因分析模型
SQL查询入门SQL
问题
分析用户转化路径,使用不同归因模型(首次点击、末次点击、线性)评估各渠道贡献。
答题要点
WITH
-- 用户触点路径
user_touchpoints AS (
SELECT
user_id,
touchpoint_id,
channel,
touchpoint_time,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY touchpoint_time) AS touch_sequence,
COUNT(*) OVER (PARTITION BY user_id) AS total_touches
FROM marketing_touchpoints
WHERE touchpoint_time >= '2024-01-01'
),
-- 转化事件
conversions AS (
SELECT
user_id,
order_id,
order_date AS conversion_date,
amount AS conversion_value
FROM orders
WHERE status = 'completed'
AND order_date >= '2024-01-01'
),
-- 关联转化前7天内的触点
conversion_paths AS (
SELECT
c.user_id,
c.order_id,
c.conversion_date,
c.conversion_value,
t.touchpoint_id,
t.channel,
t.touchpoint_time,
t.touch_sequence,
t.total_touches,
CASE WHEN t.touch_sequence = 1 THEN 1 ELSE 0 END AS is_first_touch,
CASE WHEN t.touch_sequence = t.total_touches THEN 1 ELSE 0 END AS is_last_touch
FROM conversions c
INNER JOIN user_touchpoints t
ON c.user_id = t.user_id
AND t.touchpoint_time <= c.conversion_date
AND t.touchpoint_time >= DATE_SUB(c.conversion_date, INTERVAL 7 DAY)
),
-- 归因计算
attribution AS (
SELECT
order_id,
channel,
conversion_value,
total_touches,
is_first_touch,
is_last_touch,
-- 首次点击归因
CASE WHEN is_first_touch = 1 THEN conversion_value ELSE 0 END AS first_click_value,
-- 末次点击归因
CASE WHEN is_last_touch = 1 THEN conversion_value ELSE 0 END AS last_click_value,
-- 线性归因(平均分配)
conversion_value / total_touches AS linear_value,
-- 时间衰减归因(越接近转化权重越高)
conversion_value * POWER(2, -1.0 * (total_touches - touch_sequence)) /
SUM(POWER(2, -1.0 * (total_touches - touch_sequence))) OVER (PARTITION BY order_id)
AS time_decay_value,
-- U型归因(首末各40%,中间20%)
CASE
WHEN total_touches = 1 THEN conversion_value
WHEN total_touches = 2 THEN conversion_value * 0.5
WHEN is_first_touch = 1 OR is_last_touch = 1 THEN conversion_value * 0.4
ELSE conversion_value * 0.2 / (total_touches - 2)
END AS u_shaped_value
FROM conversion_paths
)
-- 按渠道汇总不同归因模型下的贡献
SELECT
channel,
COUNT(DISTINCT order_id) AS conversions,
SUM(conversion_value) AS total_conversion_value,
ROUND(SUM(first_click_value), 2) AS first_click_attribution,
ROUND(SUM(last_click_value), 2) AS last_click_attribution,
ROUND(SUM(linear_value), 2) AS linear_attribution,
ROUND(SUM(time_decay_value), 2) AS time_decay_attribution,
ROUND(SUM(u_shaped_value), 2) AS u_shaped_attribution,
ROUND(SUM(first_click_value) / SUM(conversion_value) * 100, 2) AS first_click_pct,
ROUND(SUM(last_click_value) / SUM(conversion_value) * 100, 2) AS last_click_pct,
ROUND(SUM(linear_value) / SUM(conversion_value) * 100, 2) AS linear_pct
FROM attribution
GROUP BY channel
ORDER BY linear_attribution DESC;
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题