获取每个班级最多编号的学生列表

时间:2012-09-08 13:11:20

标签: mysql sql

我想从db中获取学生列表,他们在每个班级中都有学生姓名获得最大数量。使用MySQL DB。

我有以下表格,如学生,班级,结果(具有不同的年份结果)

表结构学生(student_id,student_name,class_id,地址),类(class_id,class_name),结果(result_id,student_id,year,marks)

我需要列表

Student Name   class   Marks
Jon            A-1      800
Steve          B-1      789

3 个答案:

答案 0 :(得分:4)

修改更正的代码,评论正确

尝试使用此SQL Fiddle link

上的代码

答案 1 :(得分:3)

您可以使用子查询来过滤每班最高分的学生:

select  s.student_name
,       c.class_name
,       r.marks
from    results r
join    student s
on      r.student_id = s.student_id
join    class c
on      c.class_id = s.class_id
where   r.result_id =
        (
        select  r2.result_id
        from    student s2
        join    results r2
        on      s2.student_id = r2.student_id
        where   c.class_id = s2.class_id
        order by
                r2.marks desc
        limit   1
        )

Live example at SQL Fiddle.

答案 2 :(得分:1)

select s1.student_name, c1.class_name, r1.marks 
from student s1, class c1, results r1,
  (select s2.class_id, max(r2.marks) marks 
   from results r2, student s2
   where r2.student_id = s2.student_id 
   group by s2.class_id) agg
where r1.marks      = agg.marks 
  and r1.student_id = s1.student_id
  and s1.class_id   = c1.class_id
  and s1.class_id   = agg.class_id