各个视频的平均完播率

明确题意:

计算2021年里有播放记录的每个视频的完播率,并按完播率降序排序


问题分解:

  • 关联用户-视频互动记录和短视频信息表:JOIN tb_video_info USING(video_id);
  • 筛选2021年的记录:WHERE YEAR(start_time)=2021
  • 按视频id分组:GROUP BY video_id
  • 计算每条播放记录是否完成播放:IF(TIMESTAMPDIFF(SECOND, start_time, end_time)>=duration, 1, 0)
  • 计算完播率,完成播放为1,未完成播放为0,取平均即为完播率AVG()
  • 保留3位小数:ROUND(x, 3)

细节问题:

  • 表头重命名:as
  • 按完播率倒序排序:ORDER BY avg_comp_play_rate DESC;

完整代码:

SELECT video_id, ROUND(AVG(IF(
        TIMESTAMPDIFF(SECOND, start_time, end_time)>=duration, 1, 0
    )), 3) as avg_comp_play_rate
FROM tb_user_video_log
JOIN tb_video_info USING(video_id)
WHERE YEAR(start_time)=2021
GROUP BY video_id
ORDER BY avg_comp_play_rate DESC;