sql最大功能用法

时间:2019-03-26 15:44:29

标签: sql sql-server group-by

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

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

,但是此查询没有提供与我想要的结果相同的结果,因此我需要一个查询才能获得如上所示的结果, 感谢您的帮助。

3 个答案:

答案 0 :(得分:4)

看一下您的样本,您似乎需要在子查询中连接最大值组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

答案 1 :(得分:1)

为什么不简单地使用ROW_NUMBER()DENSE_RANK()? :

SELECT t.*
FROM (SELECT t.*, ROW_NUMBER() OVER (PARTITION BY ExamType ORDER BY Value DESC) AS SEQ
      FROM TableExam t
     ) t
WHERE SEQ = 1;

如果您与Value有联系,则应改用DENSE_RANK()

答案 2 :(得分:0)

您可以使用row_number()窗口功能

 with cte1 as
    ( select *,row_number()over (partition by ExamType   order by Value desc ) rn
     from TableExam
    ) select ExamType,year(date1) as Year, Value from cte1 where rn=1
    order by year(date1) dese

使用子查询

   Select * from (Select *,row_number()over(partition by ExamType 
   order by Value desc) rn from TableExam ) a
   Where rn=1
   Order by date1 desc


ExamType    Year    value
IELTS      2019     240
TOELF      2017     100
GMAT       2016     70

demo link