with a as( --创建临时表,用于进行查询top3的操作
select month(t1.fdate) as month,t3.song_id,
t3.song_name song_name,count(*) play_pv
from(
select fdate,user_id,song_id --时间是2022年的
from play_log
where year(fdate)=2022
)as t1,(
select user_id,age --用户年龄是18-25岁之间的
from user_info
where age between 18 and 25
)as t2,(
select song_id,song_name --歌曲是周杰伦的
from song_info
where singer_name='周杰伦'
)as t3
where t1.user_id=t2.user_id and t1.song_id=t3.song_id
group by month,t3.song_name,t3.song_id --按照月份、歌曲名字,歌曲Id进行分组
order by month asc,play_pv desc,t3.song_id asc--分组后,按照月份、播放次数、歌曲Id进行分组
)
select b.month,b.ranking,b.song_name,b.play_pv
from(
select *,ROW_NUMBER() over(partition by a.month order by a.play_pv desc) as ranking
--ROW_NUMBER()窗口函数的用法
from a
)b
where b.ranking<=3