select name, subject, score
from grades
order by subject, score desc
数据如下:
然后,每个科目按照分组排序
select (@i:=case when @subject_pre=t1.subject then @i+1 else 1 end) as rn,
t1.*,
(@subject_pre:=subject)
from (
select name, subject, score
from grades
order by subject, score desc
) t1,
(select @i:=0, @subject_pre:='') as t2
group by subject, score
order by subject, score desc
select name, subject, score from(
select (@i:=case when @subject_pre=t1.subject then @i+1 else 1 end) as rn,
t1.name,
t1.subject,
t1.score,
(@subject_pre:=subject)
from (
select name, subject, score
from grades
order by subject, score desc
) t1,
(select @i:=0, @subject_pre:='') as t2
group by subject, score
order by subject, score desc
) t
where rn=2