-- 使用 with 子句来提高可读性和性能
with t as (
select
month(p.fdate) as month, -- 提取月份
row_number() over (partition by month(p.fdate) order by count(s.song_name) desc, p.song_id asc) as ranking, -- 计算排名
s.song_name, -- 歌曲名称
count(s.song_name) as play_pv -- 播放次数
from play_log p
left join song_info s on p.song_id = s.song_id -- 连接歌曲信息表
left join user_info u on p.user_id = u.user_id -- 连接用户信息表
where
u.age between 18 and 25 -- 年龄在18到25岁之间
and s.singer_name = '周杰伦' -- 歌手是周杰伦
and year(p.fdate) = '2022' -- 日期在2022年
group by month(p.fdate), s.song_name, p.song_id -- 按月份、歌曲名称和歌曲ID分组
)
-- 选择排名前3的记录
select
month, -- 月份
ranking, -- 排名
song_name, -- 歌曲名称
play_pv -- 播放次数
from t
where ranking <= 3; -- 只选择排名前3的记录