从 mysql table 和 last.fm 涂鸦中找出给定年份的前 100 名

Finding Top-100 of a given year from a mysql table with last.fm scrobbles

我向 MariaDB table 导入了一个 CSV 文件 by this tool,其中包含我所有的 last.fm 涂鸦,创建脚本如下:

CREATE TABLE `scrobbles` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `artist` VARCHAR(128) NULL DEFAULT '',
    `album` VARCHAR(128) NULL DEFAULT '',
    `title` VARCHAR(128) NULL DEFAULT '',
    `datahora` DATETIME NULL DEFAULT current_timestamp(),
    PRIMARY KEY (`id`)
)ENGINE=InnoDB;

我想知道如何获得给定年份执行次数最多的曲目(基本上是标题+艺术家组合重复次数最多),按每首曲目的 plays/scrobbles 的数量排序。

如果你想要这个一年,你可以聚合,排序和限制:

select artist, album, title, count(*) cnt
from scrobbles
where datahora >= '2019-01-01' and datahora < '2020-01-01'
group by artist, album, title
order by count(*) desc limit 100

我将专辑添加到 group by 子句中,因为人们可能会认为不同专辑的标题同音。

如果你想要一次使用多年,那么我会推荐 window 函数:

select *
from (
    select artist, album, title, year(datahora) yr, count(*) cnt,
        rank() over(partition by year(datahora) order by count(*) desc) rn
    from scrobbles
    group by artist, album, title
) t
where rn <= 100
order by yr, cnt desc

这种方法的另一个好处是它允许底部连接;如果碰巧在最后一个位置出现平局,那么每年可能 return 超过 100 行。