有两种 第一种是比较简单的 用sum()开窗求累加 很多人都写出来了 我就不写了
第二中 通过自 join 实现累加
with t1 as (
select author,
DATE_FORMAT(start_time, '%Y%m') as month,
sum(if(if_follow=2,-1 ,if_follow)) total_fans,
count(1) log_count
from tb_user_video_log a
join tb_video_info b
using(video_id)
group by author,DATE_FORMAT(start_time, '%Y%m')
order by author,total_fans
) ,
t2 as (
select a.author, a.month,sum(b.total_fans) total_fans
from t1 a join t1 b
on a.author=b.author and PERIOD_DIFF(a.month,b.month) >=0
group by a.author, a.month),
t3 as (
select author, month, round( t1.total_fans/log_count,3) avg_res from t1 group by author, month
),
t4 as (
select author, month, max(total_fans) total_fans from t2 group by author, month
)
select author,concat( left(month,4),'-',right(month,2)) month,avg_res as fans_growth_rate,total_fans
from t3 left join t4 using (author,month) where total_fans >0 order by author,total_fans
select author,
DATE_FORMAT(start_time, '%Y%m') as month,
sum(if(if_follow=2,-1 ,if_follow)) total_fans,
count(1) log_count
from tb_user_video_log a
join tb_video_info b
using(video_id)
group by author,DATE_FORMAT(start_time, '%Y%m')
order by author,total_fans
) ,
t2 as (
select a.author, a.month,sum(b.total_fans) total_fans
from t1 a join t1 b
on a.author=b.author and PERIOD_DIFF(a.month,b.month) >=0
group by a.author, a.month),
t3 as (
select author, month, round( t1.total_fans/log_count,3) avg_res from t1 group by author, month
),
t4 as (
select author, month, max(total_fans) total_fans from t2 group by author, month
)
select author,concat( left(month,4),'-',right(month,2)) month,avg_res as fans_growth_rate,total_fans
from t3 left join t4 using (author,month) where total_fans >0 order by author,total_fans

京公网安备 11010502036488号