select
month,
ranking,
song_name,
play_pv
from
(
select
month(fdate) as month,
ROW_NUMBER() over (PARTITION BY month(fdate) ORDER BY count(play_log.song_id) DESC,song_info.song_id ASC) as ranking,
song_name,
count(play_log.song_id) as play_pv,
song_info.song_id
from 
play_log,song_info,user_info
where 
play_log.song_id = song_info.song_id
and
play_log.user_id = user_info.user_id
AND
year(fdate) = 2022
AND
age between 18 and 25
AND
singer_name = "周杰伦"
group by month(fdate),song_name,song_info.song_id)t
WHERE
ranking <= 3
ORDER BY
    month ASC, play_pv DESC;

知识点:窗口函数ORDER BY 可以进行两次排名

  • PARTITION BY MONTH(p.fdate):按月份分区。
  • ORDER BY COUNT(*) DESC, s.song_id ASC按播放次数降序排列,如果播放次数相同,则按歌曲ID升序排列

知识点:聚合函数count(),要求使用group by,因本例需要按照月份、歌曲分组计算播放量

易错点 :在where语句中使用了窗口函数,得在外层包一层查询