sql - Joining tables based on the maximum value -


A simplified example of what I'm talking about:

  table : Examinations of students _____________ ____________________________________ | ID | Name | | ID | Student_id | Score | Date | | ---- + ------ | | ---- + ------------ + ------- + -------- | | 1 | Gym | | 1 | 1 | 73 | 8/1/09 | | 2 | Joe | 2 | 1 | 67 | 9/2/09 | | 3 | Jai | | 3 | 1 | 93 | 1/3/09 | | ____ | ______ | | 4 | 2 | 27 | 4/9/09 | | 5 | 2 | 17 | 8/9/09 | | 6 | 3 | 100 | 1/6/09 | | ____ | ____________ | _______ | ________ |  

For this question, suppose at least one exam result has been recorded in each student.

How do you choose each student with them the highest score? Edit : ... and other fields in that record?

Expected Output:

  _________________________ | Name | Score | Date | | ------ + ------- | -------- | | Gym | 93 | 1/3/09 | | Joe 27 | 4/9/09 | | Jai | 100 | 1/6/09 | | ______ | _______ | ________ |  

Welcome to all types of DBMS.

Answering the edited question (i.e. also obtaining related columns).

In SQL Server 2005+, the best way would be to use a combination with this one like this:

  as exam_data (r.student_id, r. Score, r.date, row_number ()) (r.student_id by division by r.score desc), select exam_results r as sn, s.name, d.score, d.date, d.student_id students To join exam_data d s.id = d.student_id where d.rn = 1;  

For ANSI-SQL compliance solutions, a subquery and self-matching will work, such as:

  select s.name, r.student_id , From r.score, r.date (choose r.student_id, by r.student_id by exam_results r group max_score as max) by joining exam_results at r.student_id = d.student_id and r.score = d. Join Max_score students at s.id = r.student_id;  

This final form holds that the student_id / max_core combination is not duplicate, if and / or you want to plan to de-duplicate them, You will need to use to decide which drag to connect with some determinism. For example, suppose that if you want to break a tie based on the most recent maximum score, then the same There may not be many records for a given student with the status, so you do something like:

  select s.name, r3.student_id, r3.score, r3.date , From r3.other_column_a, ... select (r2.student_id, from max_score as r2.score, max (r2.date) as max_score_max_date (R1.student_id, max (r1.score) from exam_results r1 group R1.student_id as max_score) r2.student_id = d.student_id and r2.score = d.max_score at group r2.student_id, r2 at exam_results r2. Score) r may include exam_results r3 r3 .student_id = r.student_id and r3.score = r.max_score and r3.date = r.max_score_max Join students at _date s.id = r3.student_id;  

Edit: Added a proper de-duplication query thanks to the good catch of Mark in the comment


Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

php - Multiple Select with Explode: only returns the word "Array" -

php - jQuery AJAX Post not working -