目录
数据表描述
问题描述
输出示例
解题思路【重点】
正解代码
有以下两张表:
表1:用户-视频互动表tb_user_video_log
数据举例:
说明:
表2:短视频信息表tb_video_info
数据举例:
说明:
计算2021年里有播放记录的每个视频的完播率(结果保留三位小数),并按完播率降序排序
注:视频完播率是指完成播放次数占总播放次数的比例。简单起见,结束观看时间与开始播放时间的差>=视频时长时,视为完成播放。
说明:
视频id2001在2021年10月有3次播放记录,观看时长分别为30秒、24秒、34秒,视频时长30秒,因此有两次是被认为完成播放了的,故完播率为0.667;
视频id2002在2021年9月和10月共2次播放记录,观看时长分别为42秒、30秒,视频时长60秒,故完播率为0.000。
首先,我们来分解问题:
各个要求如何解:
回顾,MySQL中各个关键字的执行顺序:
from>on>join>where>group by>with>having>select>distinct>order by>limit
我们接下来,就根据这个关键字顺序来写:
from tb_user_video_log a,tb_video_info b
#顺便给重命名了一下
from tb_user_video_log a,tb_video_info b
where a.video_id = b.video_id and year(start_time) = 2021
from tb_user_video_log a,tb_video_info b
where a.video_id = b.video_id and year(start_time) = 2021
group by a.video_id
select a.video_id,
round(sum(if(end_time - start_time >= duration,1,0))/count(*),3)
as avg_comp_play_rate
from tb_user_video_log a,tb_video_info b
where a.video_id = b.video_id and year(start_time) = 2021
group by a.video_id
select a.video_id,
round(sum(if(end_time - start_time >= duration,1,0))/count(*),3)
as avg_comp_play_rate
from tb_user_video_log a,tb_video_info b
where a.video_id = b.video_id and year(start_time) = 2021
group by a.video_id
order by avg_comp_play_rate desc;
所有代码就结束了,拿去运行就可以了~
select a.video_id,
round(sum(if(end_time - start_time >= duration,1,0))/count(*),3)
as avg_comp_play_rate
from tb_user_video_log a,tb_video_info b
where a.video_id = b.video_id and year(start_time) = 2021
group by a.video_id
order by avg_comp_play_rate desc;
或者:
select a.video_id,
round(sum(if(end_time - start_time >= duration,1,0))/count(*),3)
as avg_comp_play_rate
from tb_user_video_log a left join tb_video_info b on a.video_id = b.video_id
where year(start_time) = 2021
group by a.video_id
order by avg_comp_play_rate desc;
好啦,本期就到这里了,下期见~