Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Holen Sie sich Top-k jeder Gruppe in MySQL

Probieren Sie es aus:

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 hier