从听歌流水中找到18-25岁用户在2022年每个月播放次数top 3的周杰伦的歌曲
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 256M,其他语言512M
示例1
输入例子:
drop table if exists play_log; create table `play_log` ( `fdate` date, `user_id` int, `song_id` int ); insert into play_log(fdate, user_id, song_id) values ('2022-01-08', 10000, 0), ('2022-01-16', 10000, 0), ('2022-01-20', 10000, 0), ('2022-01-25', 10000, 0), ('2022-01-02', 10000, 1), ('2022-01-12', 10000, 1), ('2022-01-13', 10000, 1), ('2022-01-14', 10000, 1), ('2022-01-10', 10000, 2), ('2022-01-11', 10000, 3), ('2022-01-16', 10000, 3), ('2022-01-11', 10000, 4), ('2022-01-27', 10000, 4), ('2022-02-05', 10000, 0), ('2022-02-19', 10000, 0), ('2022-02-07', 10000, 1), ('2022-02-27', 10000, 2), ('2022-02-25', 10000, 3), ('2022-02-03', 10000, 4), ('2022-02-16', 10000, 4); drop table if exists song_info; create table `song_info` ( `song_id` int, `song_name` varchar(255), `singer_name` varchar(255) ); insert into song_info(song_id, song_name, singer_name) values (0, '明明就', '周杰伦'), (1, '说好的幸福呢', '周杰伦'), (2, '江南', '林俊杰'), (3, '大笨钟', '周杰伦'), (4, '黑键', '林俊杰'); drop table if exists user_info; create table `user_info` ( `user_id` int, `age` int ); insert into user_info(user_id, age) values (10000, 18)
输出例子:
month|ranking|song_name|play_pv 1|1|明明就|4 1|2|说好的幸福呢|4 1|3|大笨钟|2 2|1|明明就|2 2|2|说好的幸福呢|1 2|3|大笨钟|1
例子说明:
1月被18-25岁用户播放次数最高的三首歌为“明明就”、“说好的幸福呢”、“大笨钟”,“明明就”和“说好的幸福呢”播放次数相同,排名先后由两者的song_id先后顺序决定。2月同理。
解析:首先需要从play_log表中筛选出18-25岁用户在2022年每个月的播放记录,然后按照月份和歌曲ID进行分组统计播放次数,最后按照播放次数降序排列并取前三名。
代码如下:
SELECT
DATE_FORMAT(fdate, '%Y-%m') AS month,
song_id,
song_name,
COUNT(*) AS play_pv
FROM
play_log pl
JOIN
song_info si ON pl.song_id = si.song_id
WHERE
pl.user_id IN (
SELECT user_id FROM user_info WHERE age BETWEEN 18 AND 25
) AND YEAR(fdate) = 2022
GROUP BY
month, song_id
ORDER BY
month, play_pv DESC;