2

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

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

表结构 student(student_id,student_name,class_id,address), class(class_id,class_name), results(result_id,student_id,year,marks)

我需要像这样的清单

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

3 回答 3

4

编辑更正的代码,注释正确

试试这个SQL Fiddle 链接上的代码

于 2012-09-08T13:49:17.903 回答
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
        )

SQL Fiddle 上的实时示例。

于 2012-09-08T13:57:16.443 回答
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
于 2012-09-08T14:08:16.407 回答