在排序的MS Access查询中为记录分配排名/索引

时间:2018-02-01 21:06:07

标签: vba ms-access access-vba

我有一个MS Access查询,我正在使用无法出于保密原因输出的数据进行排序,但是,我需要在输出中包含排名或索引,以便可以维护排序顺序。

目前,我的方法基本如下:

Dim cdb As DAO.Database
Dim rst As DAO.Recordset
Dim dst As DAO.Recordset
Dim idx As Long

Set cdb = CurrentDb
Set rst = cdb.OpenRecordset("SELECT Field1, Field2, Field3, Field4, Field5 FROM MyTable ORDER BY Field6")
Set dst = cdb.OpenRecordset("MyOutputTable")
idx = 1

If Not rst.EOF Then
    rst.MoveFirst
    Do Until rst.EOF
        dst.AddNew
        dst!Field1 = rst!Field1
        dst!Field2 = rst!Field2
        dst!Field3 = rst!Field3
        dst!Field4 = rst!Field4
        dst!Field5 = rst!Field5
        dst!Rank = idx
        dst.Update
        idx = 1 + idx
        rst.MoveNext
    Loop
End If
dst.Close
rst.Close

Set dst = Nothing
Set rst = Nothing
Set cdb = Nothing

然而:

  • 这需要创建一个输出表,其中包含预先存在的“排名”字段以存储结果。

  • Do循环中填充输出表中每个字段的值非常繁琐......必须有更好的方法!

因此,我的问题是这个结果是否只能使用查询获得,而且没有世俗的VBA?

非常感谢您的时间和提前帮助

3 个答案:

答案 0 :(得分:1)

是的,您可以使用查询来使用子查询来实现此结果:

SELECT Field1, Field2, Field3, Field4, Field5, 
(
SELECT Count(s.Field6)
FROM MyTable s
WHERE s.Field6 <= t.Field6
) As Rank
FROM MyTable t
ORDER BY Field6

请注意,这会对性能产生重大影响,因为每个行都需要重新查询子查询。

另请注意,对于Field6具有相等值的行,它们的等级将相等,与其等级不相等的VBA代码形成对比。

答案 1 :(得分:1)

您可以使用我的 RowCounter 功能。有关典型用法,请参阅内嵌注释:

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

答案 2 :(得分:0)

从@ Gustav的解决方案中学习,我意识到因为我实际上并没有计算由密钥聚合的记录,而只是为排序集分配排名或索引,所以我可以使用以下简单的VBA代码:

Function RowRank(Optional varTmp, Optional bolRst As Boolean) As Long
    Static lngRow As Long
    If bolRst Then lngRow = 0 Else lngRow = 1 + lngRow
    RowRank = lngRow
End Function

使用以下SQL语句进行评估:

SELECT 
    t.*, RowRank([Field6]) AS Rank
FROM 
    (SELECT * FROM MyTable ORDER BY Field6) AS t
WHERE 
    RowRank("",True) = 0

这里,RowRank函数在WHERE子句中初始化,并且RowRank语句中提供给SELECT函数的第一个参数仅仅是伪参数为了强制对表RowRank中的每条记录评估t函数。