【SQL真题】SQL3:每类视频近一个月的转发量/率
题目:
自己写的:
select a.tag, retweet_cut, retweet_rate from ( select info.tag, sum(if_retweet) as retweet_cut, round(sum(if_retweet)/count(*),3) as retweet_rate from tb_user_video_log log join tb_video_info info on log.video_id=info.video_id group by tag having date(start_time)<timestampdiff(max(date(start_time),interval 30)) ) a order by retweet_rate desc
存在的问题:
计算日期用起始日期
timstampdiff的用法
SQL结构的写法【能用简单不用复合】
where中找最大最小【如何用聚合函数】
思路1:
select info.tag, sum(if_retweet) as retweet_cut, round(sum(if_retweet)/count(*),3) as retweet_rate from tb_user_video_log log join tb_video_info info on log.video_id=info.video_id where timestampdiff(day,date(start_time),date((select max(start_time) from tb_user_video_log)))<=29 group by tag order by retweet_rate desc
思路2:窗口函数构建临时表
with play_time as (select video_id,start_time,max(start_time) over () as max_play_time,if_retweet from tb_user_video_log) select tag,sum(if_retweet),round(sum(if_retweet)/count(*),3) as retweet_rate from play_time t1,tb_video_info t2 where t1.video_id=t2.video_id and TIMESTAMPDIFF(day,start_time,max_play_time) < 30 group by tag order by retweet_rate desc
本文来自博客园,作者:哥们要飞,转载请注明原文链接:https://www.cnblogs.com/liujinhui/p/16381238.html