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

So finden Sie die Top 3 Topper jedes Fachs in der angegebenen Tabelle

Sie können dies mithilfe von Variablen tun.

select t.*
from (select t.*,
             (@rn := if(@s = subject, @rn + 1,
                        if(@s := subject, 1, 1)
                       )
             ) as rn
      from t cross join
           (select @rn := 0, @s := '') params
      order by subject, marks desc
     ) t 
where rn <= 3
order by t.subject, t.rn;