簡體   English   中英

獲取每個班級最多編號的學生列表

[英]Get list of students with max number in each class

我想從db中獲取學生列表,他們在每個班級中都有學生姓名獲得最大數量。 使用MySQL DB。

我有以下表格,如學生,班級,結果(不同年份的結果)

表結構student(student_id,student_name,class_id,address),類(class_id,class_name),結果(result_id,student_id,year,marks)

我需要列表

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

編輯更正的代碼,評論是正確的

嘗試使用此SQL Fiddle鏈接上的代碼

您可以使用子查詢來過濾每班最高分的學生:

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的實例。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM