如何根据新记录的排名更新具有预定义排名的列?

时间:2016-12-27 18:49:16

标签: sql-update ms-access-2010

我有一个MS Access 2010应用程序,它写回(后端)sql server。该表具有学生ID,测试分数和排名为列。该应用程序有一个表单,它接受用户的输入。当新学生输入他/她的ID,分数和排名时,根据插入的排名,其他职级必须更新。

例如,如果新学生的得分为79分,等级为5分,那么当前5分的学生必须改为6分,第6分为第7分,依此类推,在SQL表中

在:

Student_ID  Score Rank
1            89    1
16           88    2
25           84    3
3            81    4
7            78    5
15           75    6
12           72    7
17           70    8
56           65    9
9            64    10

后:

Student_ID  Score Rank
1            89    1
16           88    2
25           84    3
3            81    4
7            78    6
15           75    7
12           72    8
17           70    9
56           65    10
9            64    11
10           75    5

1 个答案:

答案 0 :(得分:0)

删除排名字段并创建一个动态计算排名(行号)的查询。要加快速度,请使用如下所示的集合:

Public Function RowCounter( _
  ByVal strKey As String, _
  ByVal booReset As Boolean, _
  Optional ByVal strGroupKey As String) _
  As Long

' Builds consecutive RowIDs in select, append or create query
' with the possibility of automatic reset.
' Optionally a grouping key can be passed to reset the row count
' for every group key.
'
' Usage (typical select query):
'   SELECT RowCounter(CStr([ID]),False) AS RowID, *
'   FROM tblSomeTable
'   WHERE (RowCounter(CStr([ID]),False) <> RowCounter("",True));
'
' Usage (with group key):
'   SELECT RowCounter(CStr([ID]),False,CStr[GroupID])) AS RowID, *
'   FROM tblSomeTable
'   WHERE (RowCounter(CStr([ID]),False) <> RowCounter("",True));
'
' The Where statement resets the counter when the query is run
' and is needed for browsing a select query.
'
' Usage (typical append query, manual reset):
' 1. Reset counter manually:
'   Call RowCounter(vbNullString, False)
' 2. Run query:
'   INSERT INTO tblTemp ( RowID )
'   SELECT RowCounter(CStr([ID]),False) AS RowID, *
'   FROM tblSomeTable;
'
' Usage (typical append query, automatic reset):
'   INSERT INTO tblTemp ( RowID )
'   SELECT RowCounter(CStr([ID]),False) AS RowID, *
'   FROM tblSomeTable
'   WHERE (RowCounter("",True)=0);
'
' 2002-04-13. Cactus Data ApS. CPH
' 2002-09-09. Str() sometimes fails. Replaced with CStr().
' 2005-10-21. Str(col.Count + 1) reduced to col.Count + 1.
' 2008-02-27. Optional group parameter added.
' 2010-08-04. Corrected that group key missed first row in group.

  Static col      As New Collection
  Static strGroup As String

  On Error GoTo Err_RowCounter

  If booReset = True Then
    Set col = Nothing
  ElseIf strGroup <> strGroupKey Then
    Set col = Nothing
    strGroup = strGroupKey
    col.Add 1, strKey
  Else
    col.Add col.Count + 1, strKey
  End If

  RowCounter = col(strKey)

Exit_RowCounter:
  Exit Function

Err_RowCounter:
  Select Case Err
    Case 457
      ' Key is present.
      Resume Next
    Case Else
      ' Some other error.
      Resume Exit_RowCounter
  End Select

End Function

研究典型用法的在线评论。