题目:
每个月Top3的周杰伦歌曲
从听歌流水中找到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月同理。
代码:
select
if(substring(month,1,1)='0',substring(month,2,1),month) as month ,
ranking,
song_name,
play_pv
from
(
select
substring(p.fdate,6,2)as month,
row_number() over (partition by substring(p.fdate,6,2) order by count(*) desc, s.song_id ) as ranking ,
song_name,
count(*) as play_pv
from play_log p
join song_info s on p.song_id =s.song_id
join user_info u on u.user_id = p.user_id
where
p.fdate >= '2022-01-01' and p.fdate<='2023-01-01'
and u.age<='25'and u.age>='18'
and s.singer_name ='周杰伦'
group by s.song_id,song_name,substring(p.fdate,6,2)
order by substring(p.fdate,6,2),play_pv desc ,s.song_id
) t
where ranking<=3
写的很烂,子查询加3个连接,有优化的空间,谢谢大佬指正。