Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Answering the EDITED question (i.e. to get associated columns as well).</p> <p>In Sql Server 2005+, the best approach would be to use a <a href="http://msdn.microsoft.com/en-us/library/ms189798.aspx" rel="noreferrer">ranking/window function</a> in conjunction with a <a href="http://msdn.microsoft.com/en-us/library/ms190766.aspx" rel="noreferrer">CTE</a>, like this:</p> <pre><code>with exam_data as ( select r.student_id, r.score, r.date, row_number() over(partition by r.student_id order by r.score desc) as rn from exam_results r ) select s.name, d.score, d.date, d.student_id from students s join exam_data d on s.id = d.student_id where d.rn = 1; </code></pre> <p>For an ANSI-SQL compliant solution, a subquery and self-join will work, like this:</p> <pre><code>select s.name, r.student_id, r.score, r.date from ( select r.student_id, max(r.score) as max_score from exam_results r group by r.student_id ) d join exam_results r on r.student_id = d.student_id and r.score = d.max_score join students s on s.id = r.student_id; </code></pre> <p>This last one assumes there aren't duplicate student_id/max_score combinations, if there are and/or you want to plan to de-duplicate them, you'll need to use another subquery to join to with something deterministic to decide which record to pull. For example, assuming you can't have multiple records for a given student with the same date, if you wanted to break a tie based on the most recent max_score, you'd do something like the following:</p> <pre><code>select s.name, r3.student_id, r3.score, r3.date, r3.other_column_a, ... from ( select r2.student_id, r2.score as max_score, max(r2.date) as max_score_max_date from ( select r1.student_id, max(r1.score) as max_score from exam_results r1 group by r1.student_id ) d join exam_results r2 on r2.student_id = d.student_id and r2.score = d.max_score group by r2.student_id, r2.score ) r join exam_results r3 on r3.student_id = r.student_id and r3.score = r.max_score and r3.date = r.max_score_max_date join students s on s.id = r3.student_id; </code></pre> <p>EDIT: Added proper de-duplicating query thanks to Mark's good catch in comments</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload