sql – 根据最大​​值连接表

这是我正在谈论的简化示例:

Table: students      exam_results
_____________       ____________________________________
| id | name |       | id | student_id | score |   date |
|----+------|       |----+------------+-------+--------|
|  1 | Jim  |       |  1 |          1 |    73 | 8/1/09 | 
|  2 | Joe  |       |  2 |          1 |    67 | 9/2/09 |
|  3 | Jay  |       |  3 |          1 |    93 | 1/3/09 |
|____|______|       |  4 |          2 |    27 | 4/9/09 |
                    |  5 |          2 |    17 | 8/9/09 |
                    |  6 |          3 |   100 | 1/6/09 |
                    |____|____________|_______|________|

为了这个问题,假设每个学生都至少记录了一个考试成绩.

你会如何选择每个学生的最高分?编辑:…和该记录中的其他字段?

预期产量:

_________________________
| name | score |   date |
|------+-------|--------|
|  Jim |    93 | 1/3/09 |
|  Joe |    27 | 4/9/09 |
|  Jay |   100 | 1/6/09 |
|______|_______|________|

欢迎使用所有类型的DBMS的答案.

回答EDITED问题(即获得相关列).

在Sql Server 2005中,最好的方法是将ranking/window functionCTE结合使用,如下所示:

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;

对于符合ANSI-SQL的解决方案,子查询和自联接将起作用,如下所示:

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;

最后一个假设没有重复的student_id / max_score组合,如果有和/或你想要去重复它们,你需要使用另一个子查询加入一个确定性的东西来决定要拉哪个记录.例如,假设您不能为具有相同日期的给定学生提供多条记录,如果您想根据最新的max_score打破平局,您可以执行以下操作:

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;

编辑:添加了正确的重复数据删除查询,感谢Mark在评论中的好评

翻译自:https://stackoverflow.com/questions/1863606/joining-tables-based-on-the-maximum-value

转载注明原文:sql – 根据最大​​值连接表