用户互动网络分析
SQL数据分析入门SQL
问题
分析用户互动关系网络,识别KOL(关键意见领袖)和核心社群。
答题要点
WITH user_interactions AS (
SELECT
from_user_id,
to_user_id,
COUNT(*) AS interaction_count,
SUM(CASE WHEN action_type = 'like' THEN 1 ELSE 0 END) AS likes,
SUM(CASE WHEN action_type = 'comment' THEN 1 ELSE 0 END) AS comments,
SUM(CASE WHEN action_type = 'share' THEN 1 ELSE 0 END) AS shares
FROM user_interaction_log
WHERE action_time >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
GROUP BY from_user_id, to_user_id
),
user_influence AS (
SELECT
to_user_id AS user_id,
COUNT(DISTINCT from_user_id) AS follower_count, -- 入度(被互动)
SUM(interaction_count) AS total_interactions_received,
SUM(likes) AS total_likes_received,
SUM(comments) AS total_comments_received,
SUM(shares) AS total_shares_received
FROM user_interactions
GROUP BY to_user_id
),
user_activity AS (
SELECT
from_user_id AS user_id,
COUNT(DISTINCT to_user_id) AS following_count, -- 出度(主动互动)
SUM(interaction_count) AS total_interactions_sent
FROM user_interactions
GROUP BY from_user_id
),
user_metrics AS (
SELECT
COALESCE(i.user_id, a.user_id) AS user_id,
COALESCE(follower_count, 0) AS followers,
COALESCE(following_count, 0) AS following,
COALESCE(total_interactions_received, 0) AS interactions_in,
COALESCE(total_interactions_sent, 0) AS interactions_out,
COALESCE(total_likes_received, 0) AS likes_received,
-- 影响力得分:粉丝数×2 + 互动数×1 + 点赞数×0.5
(COALESCE(follower_count, 0) * 2 +
COALESCE(total_interactions_received, 0) * 1 +
COALESCE(total_likes_received, 0) * 0.5) AS influence_score
FROM user_influence i
FULL OUTER JOIN user_activity a ON i.user_id = a.user_id
)
SELECT
user_id,
followers,
following,
interactions_in,
interactions_out,
likes_received,
ROUND(influence_score, 2) AS influence_score,
CASE
WHEN influence_score >= 1000 THEN 'KOL(关键意见领袖)'
WHEN influence_score >= 500 THEN '活跃用户'
WHEN influence_score >= 100 THEN '普通用户'
ELSE '沉默用户'
END AS user_tier,
ROUND(followers * 1.0 / NULLIF(following, 0), 2) AS follower_ratio
FROM user_metrics
ORDER BY influence_score DESC
LIMIT 100;
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题