首页 > 解决方案 > sql max 函数用法

问题描述

例如,我的表中有一个值,如下所示

Id  ExamType Value Date
1   IELTS     240  2019-01-01
2   IELTS     120  2018-12-01
3   TOELF     100  2017-12-12
4   TOELF      80  2019-01-20
5   GMAT      70   2016-01-01

我希望我的查询给我这些考试的最大值,如下所示

IELTS (2019) 240
TOELF (2017) 100
GMAT  (2016) 70 

我写了我的查询如下

SELECT x.ExamType,MAX(x.Value) 
FROM TableExam x  
GROUP BY x.ExamType

但是这个查询没有给出我想要的结果,所以我需要一个查询来得到上面的结果,谢谢你的帮助。

标签: sqlsql-servergroup-by

解决方案


查看您的示例似乎您需要加入最大值组 ExampType 的子查询

select m.ExamType, year(m.date), t.max_value value
from TableExam m 
INNER JOIN (
    select ExamType, max(value) max_value
    from TableExam
    group by ExampType
) t on t.max_value = m.value and t.ExamType = m.ExamType

推荐阅读