Joining tables based on the maximum value

后端 未结 6 1707
暖寄归人
暖寄归人 2021-02-08 22:00

Here\'s a simplified example of what I\'m talking about:

Table: students      exam_results
_____________       ____________________________________
| id | name |         


        
6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-08 22:39

    Using MS SQL Server:

    SELECT name, score, date FROM exam_results
    JOIN students ON student_id = students.id
    JOIN (SELECT DISTINCT student_id FROM exam_results) T1
    ON exam_results.student_id = T1.student_id
    WHERE exam_results.id = (
        SELECT TOP(1) id FROM exam_results T2
        WHERE exam_results.student_id = T2.student_id
        ORDER BY score DESC, date ASC)
    

    If there is a tied score, the oldest date is returned (change date ASC to date DESC to return the most recent instead).

    Output:

    Jim 93  2009-01-03 00:00:00.000
    Joe 27  2009-04-09 00:00:00.000
    Jay 100 2009-01-06 00:00:00.000
    

    Test bed:

    CREATE TABLE students(id int , name nvarchar(20) );
    
    CREATE TABLE exam_results(id int , student_id int , score int, date datetime);
    
    INSERT INTO students
    VALUES
    (1,'Jim'),(2,'Joe'),(3,'Jay')
    
    INSERT INTO exam_results VALUES
    (1, 1, 73, '8/1/09'), 
    (2, 1, 93, '9/2/09'),
    (3, 1, 93, '1/3/09'),
    (4, 2, 27, '4/9/09'),
    (5, 2, 17, '8/9/09'),
    (6, 3, 100, '1/6/09')
    
    SELECT name, score, date FROM exam_results
    JOIN students ON student_id = students.id
    JOIN (SELECT DISTINCT student_id FROM exam_results) T1
    ON exam_results.student_id = T1.student_id
    WHERE exam_results.id = (
        SELECT TOP(1) id FROM exam_results T2
        WHERE exam_results.student_id = T2.student_id
        ORDER BY score DESC, date ASC)
    

    On MySQL, I think you can change the TOP(1) to a LIMIT 1 at the end of the statement. I have not tested this though.

提交回复
热议问题