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)的结果
答案 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