如何在select查询中选择与max函数结果匹配的列的值

时间:2019-05-14 11:49:53

标签: sql sql-server

我有一个表,该表具有与进行的用户测试有关的某些数据。我想从下表中获得max(testnumber)以及状态对应的max(testnumber)。

images shows the table studentchaptertest. and shows the test attented by student.i want o/p max(testnumber)=3 and its status ;1 as o/p

SELECT @LastAttemptedTest=MAX([TestNumber] FROM [dbo].[StudentChapterwiseTest] WHERE 
    [ChapterId]=584 AND [StudentId]=212045 

SELECT Status FROM [dbo].[StudentChapterwiseTest] WHERE [TestNumber]=@LastAttemptedTest AND
    [ChapterId]=584 AND [StudentId]=212045                                          

我试图在单个选择查询中获得max(testnumber)和状态对应于max(testnumber)的结果

2 个答案:

答案 0 :(得分:1)

您可以使用row_number()

select t.*
from (select t.*, row_number() over (partition by studentid order by testnumber desc) as seq
      from table t
     ) t
where seq = 1;

编辑::如果需要一行,请使用top (1)子句:

select top (1) t.*
from table t
order by t.testnumber desc;

答案 1 :(得分:0)

在子查询中选择最大测试数,然后在该子表上加入

SELECT t.status, t.testNumber
FROM StudentChapterwiseTest t
JOIN (SELECT StudentId, ChapterId, MAX(status) as max_stat 
      FROM StudentChapterwiseTest
      GROUP BY StudentId, ChapterId) mt ON t.status = mt.max_stat  AND t.chapterId = mt.chapterid AND t.studentId = mt.studentid
WHERE [ChapterId]=584 AND [StudentId]=212045