SQL:当两个字段中的记录相等时,只根据第三个字段选择一个

时间:2015-09-14 17:11:04

标签: sql ms-access

SQL查询:假设我有一个像

这样的表
Student Module Mark OtherField
1       A      23   6
1       A      40   12
2       B      76   6
2       C      87   7

(这个想法是学生可以多次重新启动学校模块) 我想只为每个模块选择最高分,即输出

Student Module Mark OtherField
1       A      40   12
2       B      76   6
2       C      87   7

即:当“学生”和“模块”字段中两个或多个记录相同时,如何选择具有最高“标记”值的记录?

4 个答案:

答案 0 :(得分:0)

怎么样:

SELECT
    t.Student,
    t.Module,
    MAX(t.Mark) AS Highest_Mark
FROM _your_student_table t
GROUP BY t.Student, t.Module

如果你需要OtherField(thx @Deepak Pawar作为提示),那么:

SELECT
    x.Student,
    x.Module,
    x.Highest_Mark,
    y.OtherField
FROM
(
    SELECT
        t.Student,
        t.Module,
        MAX(t.Mark) AS Highest_Mark
    FROM _your_student_table_ t
    GROUP BY t.Student, t.Module
) x
INNER JOIN _your_student_table_ y
  ON x.Student = y.Student AND x.Module = y.Module AND x.Highest_Mark = y.Mark

答案 1 :(得分:0)

SELECT
  table.student,
  table.module,
  max(table.Mark) highestMark
FROM
  table
GROUP BY
  table.module,
  table.student

答案 2 :(得分:0)

我不确定MS Access中使用的语法,但似乎你会使用这样的东西:

SELECT DISTINCT学生        ,模块        ,MAX(马克)        ,其他领域 FROM tbl_example GROUP BY学生           ,模块           ,其他领域

你明白了......

答案 3 :(得分:0)

我认为这正是您所寻找的,代码方式:

select
    student,
    module,
    mark,
    otherfield
from
    your_table as a
where
    mark = (select max(mark) from your_table as b where a.student = b.student and a.module = b.module);

但是,你的逻辑存在缺陷。如果学生的得分高达85分,并且得分两次,会发生什么?是否应返回otherfield的两个值?只有一个?哪一个?