找到第一次考试的分数

时间:2014-09-25 23:01:12

标签: sql-server tsql

我有多次参加考试的学生。我想返回他们带有该分数的第一个测试。

我试过这个不起作用它返回所有日期,当我删除scaledscore它返回最小日期和正确的学生ID。

我错过了什么?

SELECT StudentLocalID, MIN(AssessmentDate),scaledscore fROM dbo.Ren_sel
GROUP BY StudentLocalID,AssessmentDate,scaledscore
ORDER BY StudentLocalID

我的数据看起来像

1   02/01/2014 630
1   02/25/2014 741
2   04/01/2014 894
2   03/15/2014 759

需要的结果

1   02/01/2014 630
2   03/15/2014 759

提前致谢

3 个答案:

答案 0 :(得分:2)

SELECT StudentLocalID, AssessmentDate,scaledscore 
 FROM (
       SELECT StudentLocalID, AssessmentDate,scaledscore 
          ,ROW_NUMBER() OVER (PARTITION BY StudentLocalID ORDER BY AssessmentDate ASC) rn                      
        fROM dbo.Ren_sel
      )A
WHERE rn = 1

答案 1 :(得分:0)

一种选择是使用这样的相关子查询:

SELECT StudentLocalID, AssessmentDate, ScaledScore 
FROM Ren_sel r
WHERE AssessmentDate = 
(
    SELECT MIN(AssessmentDate) FROM Ren_sel
    WHERE StudentLocalID = r.StudentLocalID 
    GROUP BY StudentLocalID
) 

或者您可以使用派生表:

SELECT r.StudentLocalID, AssessmentDate, ScaledScore FROM Ren_sel r
INNER JOIN (
    SELECT StudentLocalID, MIN(AssessmentDate) mindate FROM Ren_sel
    GROUP BY StudentLocalID
) a ON r.StudentLocalID = a.StudentLocalID AND r.AssessmentDate = a.mindate

后者在某些情况下可能会提供更好的表现。

答案 2 :(得分:0)

除了使用排名函数和派生表之外,您还可以使用CTE(公用表格式)。

WITH C AS (
    SELECT StudentLocalID, MIN(AssessmentDate) AS firstTest fROM dbo.Ren_sel
    GROUP BY StudentLocalID
)
SELECT ren.StudentLocalID, C.firstTest, ren.scaledscore FROM dbo.Ren_sel AS ren
    INNER JOIN C
    ON ren.StudentLocalID = C.StudentLocalID
    WHERE ren.AssessmentDate = C.firstTest