用户内容消费偏好分析
SQL数据分析入门SQL
问题
分析用户对不同内容类型的消费偏好,构建内容偏好标签。
答题要点
WITH user_content_behavior AS (
SELECT
user_id,
content_type,
content_category,
COUNT(*) AS view_count,
SUM(CASE WHEN action_type = 'like' THEN 1 ELSE 0 END) AS like_count,
SUM(CASE WHEN action_type = 'comment' THEN 1 ELSE 0 END) AS comment_count,
SUM(CASE WHEN action_type = 'share' THEN 1 ELSE 0 END) AS share_count,
SUM(read_duration) AS total_duration,
AVG(read_duration) AS avg_duration
FROM user_content_log
WHERE action_time >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
GROUP BY user_id, content_type, content_category
),
user_engagement_score AS (
SELECT
user_id,
content_type,
content_category,
view_count,
-- 参与度评分:浏览×1 + 点赞×2 + 评论×3 + 分享×5 + 时长/60
(view_count * 1 + like_count * 2 + comment_count * 3 + share_count * 5 + total_duration / 60) AS engagement_score,
ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY
(view_count * 1 + like_count * 2 + comment_count * 3 + share_count * 5 + total_duration / 60) DESC
) AS preference_rank
FROM user_content_behavior
),
user_top_preferences AS (
SELECT
user_id,
GROUP_CONCAT(content_category ORDER BY preference_rank SEPARATOR ', ') AS top_categories,
GROUP_CONCAT(CONCAT(content_category, ':', ROUND(engagement_score, 0)) ORDER BY preference_rank SEPARATOR '; ') AS category_scores
FROM user_engagement_score
WHERE preference_rank <= 5
GROUP BY user_id
)
SELECT
u.user_id,
u.username,
p.top_categories AS preferred_categories,
p.category_scores,
-- 用户类型标签
CASE
WHEN p.top_categories LIKE '%科技%' THEN '科技爱好者'
WHEN p.top_categories LIKE '%娱乐%' THEN '娱乐达人'
WHEN p.top_categories LIKE '%财经%' THEN '财经关注者'
WHEN p.top_categories LIKE '%体育%' THEN '体育迷'
ELSE '泛兴趣用户'
END AS user_persona
FROM users u
JOIN user_top_preferences p ON u.user_id = p.user_id
LIMIT 100;
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题