MS Access - 不确定我获得百分位数的方式是否正常

时间:2014-09-17 07:17:24

标签: ms-access percentile

我尝试通过SQL获取MS Access中列的百分位数,但无法找到实现它的方法(可能它比我想象的要容易)。所以我编写了一个使用Recordsets而不是单个SQL查询的函数。但我仍然不确定这种方式是否正常,或者我应该继续尝试通过SQL查询获得百分位数?

Sub foo()

    Dim sCol As String, sTable As String
        sCol = "col1"
        sTable = "perc_test"

    Dim rs As Recordset
    Set rs = CurrentDb.OpenRecordset("SELECT " & sCol & " FROM " & sTable & " ORDER BY " & sCol, dbOpenSnapshot)

    With rs
    If Not (.EOF And .BOF) Then
        .MoveLast
        .MoveFirst
        For q = 0 To 0.9999999999999 Step 1 / 10
            Debug.Print getpercentile(rs, sCol, q)
        Next q
    End If
    End With

    rs.Close
    Set rs = Nothing

End Sub


Function getpercentile(ByRef rs As Recordset, ByVal sCol As String, ByVal dPerc As Double) As Double

    Dim dReturn As Double

    Dim lCount As Long
    lCount = rs.RecordCount

    With rs
    If Not (.EOF And .BOF) Then
        .MoveLast
        .MoveFirst
        .Move (Round(lCount * dPerc, 0))
        dReturn = rs.Fields(sCol).Value
    End If
    End With

    getpercentile = dReturn

End Function

到目前为止它按预期工作。是否有任何改进使其更快和/或更安全(关于错误)?

0 个答案:

没有答案