题解 | 每个月Top3的周杰伦歌曲
每个月Top3的周杰伦歌曲
https://www.nowcoder.com/practice/4ab6d198ea8447fe9b6a1cad1f671503
select sub.month, sub.ranking, sub.song_name, sub.play_pv from ( select MONTH (pl.fdate) as month, row_number() over ( partition by MONTH (pl.fdate) order by count(pl.song_id) DESC, si.song_id ) as ranking, si.song_name, count(*) as play_pv from play_log as pl join song_info as si on pl.song_id = si.song_id join user_info as ui on pl.user_id = ui.user_id where ui.age between 18 and 25 and year (pl.fdate) = 2022 and si.singer_name = '周杰伦' group by MONTH(pl.fdate), si.song_name, si.song_id ) as sub where ranking <= 3
先筛选条件 年份、年龄、歌手,
再因为每个月的前三排序,而需要窗口函数row_number()
,根据月份分区、听歌次数排序,并因为题解要求再加上歌曲id排序。
最后根据ranking前三的筛选条件,直接where
选择。
相较之前可以直接通过第三名次数where
筛选的例题,这里需要对每个月份排序,所以选择窗口函数比较好。