Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Obtenha o top-k de cada grupo no MySQL


Dê uma chance a isso:
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

Fiddle aqui