从学生中选择考试的最后一次尝试

时间:2010-11-08 20:14:40

标签: sql sql-server tsql

我有一张表,其中包含来自学生和考试的信息,每次学生参加考试时,记录都保存在此表中,所以我想从学生那里得到最后一次考试。

| IdStudent | IdTest | Attempt|
-------------------------------
| 1         | 1      | 1      |
-------------------------------
| 2         | 1      | 1      |
-------------------------------
| 1         | 1      | 2      |
-------------------------------
| 2         | 2      | 1      |

假设我选择测试编号1,我想要的记录是2和3,如果我选择测试2,我想得到的记录是4,等等。

我希望问题很清楚。 在此先感谢您的帮助。

4 个答案:

答案 0 :(得分:2)

以下SQL将为您提供所需内容:

SELECT IdStudent, IdTest, MAX(Attempt)
FROM StudentTable
WHERE IdTest = @TestNumber
GROUP BY IdStudent, IdTest

答案 1 :(得分:2)

@ Jeff的回答会得到数字而不是行。如果您想要行中的其他数据,则必须使用子查询或CTE。像这样:

WITH JeffAnswer AS
(
  SELECT IdStudent, IdTest, MAX(Attempt) AS MaxAttept
  FROM StudentTable
  WHERE IdTest = @TestNumber
  GROUP BY IdStudent, IdTest
)
SELECT * 
FROM StudentTable S
INNER JOIN JeffAnswer J ON
   S.IdStudent = J.IdStudent AND 
   S.IdTest = J.IdTest AND 
   S.Attempt = J.MaxAttempt

答案 2 :(得分:0)

Jeff Hornby的一些替代方法:

Select ...
From Table As T1
Where Exists    (
                Select 1
                From Table As T2
                Where T2.IdStudent = T1.IdStudent
                    And T2.IdTest =T1.IdTest
                Having Max(T2.Attempt) = T1.Attempt
                )

如果您使用的是SQL Server 2005 +:

With RankedTests As
    (
    Select IdStudent, IdTest, Attempt, ...
        , Row_Number() Over ( Partition By IdStudent, IdTest
                                 Order By Attempt Desc ) As Num
    From Table
    )
Select ...
From RankedTests
Where Num = 1

答案 3 :(得分:0)

我喜欢在这种情况下使用RowNumber(),因为以后很容易更改标准,而且通常比使用GROUP BY更快。

SELECT IdStudent, IdTest, Attempt  
  FROM (
          SELECT IdStudent, IdTest, Attempt, RowId = ROW_NUMBER() OVER(PARTITION BY IdStudent, IdTest ORDER BY IdStudent, IdTest, Attempt Desc)  
            FROM Student  
           WHERE IdTest = @IdTest
       ) tt  
 WHERE tt.RowId = 1