【SQL真题】SQL3:每类视频近一个月的转发量/率

题目:

https://www.nowcoder.com/practice/a78cf92c11e0421abf93762d25c3bfad?tpId=268&tqId=2285068&ru=/exam/oj&qru=/ta/sql-factory-interview/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3DSQL%25E7%25AF%2587%26topicId%3D268

自己写的:

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

 

posted @ 2022-06-16 11:04  哥们要飞  阅读(44)  评论(0编辑  收藏  举报