知识点

  1. 结果需要两个表中的数据,进行内连接
  2. 筛选2021年的数据,使用DATE_FORMAT(date,format) = 2021函数用于以不同的格式显示日期/时间数据,4位显示用"%Y"。
  3. 计算完播率,首先使用group by进行分组,使用avg(all|distinct expression)all可以省略,使用case when判别是否完播timestampdiff(interval,datetime_expr1,datetime_expr2)函数计算2个日期相差值,大于duration时为1否则为0。
  4. 最后对完播率进行降序排序

代码

select tbu.video_id, 
round(avg(
           case when timestampdiff(second, start_time, end_time) >= duration then 1 else 0 end)
          ,3) as avg_comp_play_rate
from tb_user_video_log as tbu
inner join tb_video_info as tbv
on tbu.video_id = tbv.video_id
where date_format(start_time, '%Y') = 2021
and date_format(end_time, '%Y') = 2021
group by tbu.video_id 
order by avg_comp_play_rate desc