Mysql
 sql >> Base de données >  >> RDS >> Mysql

Obtenez le top-k de chaque groupe dans MySQL

Essayez ceci :

select postid, clicks,
    @num := if(@year = @year and @month = month, @num + 1, 1) row_number,
    @year := year year, @month := month month
from (
    select * from t
    order by year, month, clicks desc
) s, (select @num := 0, @year := '', @month := '') init
group by year, month, postid, clicks
having row_number <= 2
order by year, month, clicks desc

Violon ici