【问题标题】:Get list of students with max number in each class获取每个班级人数最多的学生列表
【发布时间】:2012-09-02 02:22:29
【问题描述】:

我想从 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

【问题讨论】:

  • 我猜你错过了包含完整的表结构。
  • 如何包含更多信息,例如:数据库、版本、列、数据、预期结果、您已经尝试过的内容
  • 我正在使用 MySQL 数据库。有关更多详细信息,请更新问题

标签: mysql sql


【解决方案1】:

编辑更正代码,注释正确

试试这个SQL Fiddle link上的代码

【讨论】:

  • 现在你的学生名字是随机的。最适合 B-1 班的应该是安娜而不是史蒂夫。感谢您链接 SQL Fiddle,我重用了它!
  • 已更正,只需按类名更改[GROUP BY]子句即可按类获取最大结果
  • 是的,@Andomar 你在哪里,学生的名字是随机选择的。需要一个子查询才能正确打开,确实类似于您的解决方案,但使用MAX而不是LIMIT。修正和测试
【解决方案2】:

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

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.

【讨论】:

  • 这是另一种选择,但使用GROUP BYMAX 更清晰,你不觉得吗?
【解决方案3】:
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

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    • 1970-01-01
    • 2020-09-18
    • 2021-01-15
    • 2012-11-01
    • 1970-01-01
    相关资源
    最近更新 更多