查询返回多行而不是最大值

时间:2016-05-20 15:38:54

标签: vba ms-access access-vba

我在Access中有一个表,其中包含相关字段EFTRecID,EFTRecIDNum和CreatedBy。 EFTRecIDNum是一个自动编号字段,EFTRecID连接所需的格式" CE" &安培; EFTRedIDNum。我试图返回当前用户创建的EFTRecID字段中的最高值。为此,我尝试执行一个子查询,找到Max(EFTRecIDNum)WHERE Created =我的名字。但是,它不是返回最大值,而是以我的名字返回所有值。我知道我可以使用format选项来格式化EFTRecIDNum字段,但我需要能够以CE456格式进行搜索。

TL; DR:查询返回所有带有我姓名的记录,而不是带有我姓名的最大记录。

Public Sub DownloadMyRecords()

    Dim intI As Integer 'Used for looping in a variety of locations

    strSQL = "SELECT EFTRecID FROM tblEFTRec WHERE (SELECT MAX(EFTRecIDNum) FROM tblEFTRec WHERE CreatedBy = '" & Application.UserName & "')"

    Set cnn = New ADODB.Connection

    With cnn
        .Provider = "Microsoft.ACE.OLEDB.12.0;Data Source=" & dbLocation & "\" & dbName & ";Jet OLEDB:Database Password=" & DBPWord
        .Open dbLocation & "\" & dbName
    End With

    Debug.Print strSQL

    Set rst = New ADODB.Recordset
    rst.CursorLocation = adUseServer
    rst.Open Source:=strSQL, ActiveConnection:=cnn, _
             CursorType:=adOpenForwardOnly, LockType:=adLockOptimistic, _
             Options:=adCmdText

    Debug.Print (rst.GetString)

    rst.Close
    cnn.Close
    Set rst = Nothing
    Set cnn = Nothing

End Sub

2 个答案:

答案 0 :(得分:2)

请尝试使用此SQL语句:

strSQL = "SELECT EFTRecID 
FROM tblEFTRec 
WHERE EFTRecIDNum = (SELECT MAX(EFTRecIDNum) FROM tblEFTRec WHERE CreatedBy = '" & Application.UserName & "')"

答案 1 :(得分:1)

尝试使用:

"SELECT EFTRecID FROM tblEFTRec 
WHERE EFTRecIDNum = (SELECT MAX(EFTRecIDNum) FROM tblEFTRec 
    WHERE CreatedBy = '" & Application.UserName & "')"

以下哪些方法无效?

"SELECT MAX(EFTRecID) FROM tblEFTRec 
WHERE CreatedBy = '" & Application.UserName & "'"