SELECT tag, uid, ranking FROM ( SELECT ei.tag tag, er.uid uid, ROW_NUMBER() OVER ( PARTITION BY tag ORDER BY tag, MAX(er.score) DESC, MIN(er.score) DESC, er.uid DESC ) ranking FROM exam_record er INNER JOIN examination_info ei USING(exam_id) GROUP BY tag, uid ) tb WHERE ranking <= 3;