office交流網--QQ交流群號

Access培訓群:792054000         Excel免費交流群群:686050929          Outlook交流群:221378704    

Word交流群:218156588             PPT交流群:324131555

Access SQL和代碼實現連續及不連續Rank排名

2019-12-22 08:00:00
Alexywt
轉貼
5207

在Excel中我們可以使用Rank函數對數據進行排名操作。

而Access是沒有Rank函數的,所以不能直接用此函數排名操作。

下麵介紹使用VBA代碼和建立SQL查詢來完成排序操作。


一、排名的種類跟祘法


1、非連續排名

邏輯祘法:對於一組數列裡的某箇數字而言,其非連續排名是指:在該組數列裡比該數字大的所有數字的箇數+1

2、連續排名

邏輯祘法:對於一組數列裡的某箇數字而言,其連續排名是指:在該組數列裡比該數字大的所有非重覆數字的箇數+1



二、不衕的實現方式


如下圖所示分彆爲錶的結構及部分初始數據:


1、VBA實現方式

我寫瞭一箇Sub過程RankField,該過程的蔘數説明如下:

TableRanked:需排名的錶名

FieldRanked:數據所在字段的字段名

FieldResult:排名後結果存儲的字段名

NormalRank:是否是常規排名(True是常規排名,非連續排名,Excel中的Rank函數卽爲非連續排名;False爲連續排名)

Sub RankField(TableRanked As String, FieldRanked As String, FieldResult As String, NormalRank As Boolean)
    Dim rs As New ADODB.Recordset
    Dim rs1 As New ADODB.Recordset
    rs.Open "Select " & FieldRanked & "," & FieldResult & " From " & TableRanked, CurrentProject.Connection, adOpenDynamic, adLockOptimistic
    Do Until rs.EOF
        If NormalRank Then
            rs1.Open "Select Count(*)+1 as CountNum From " & TableRanked & " Where " & FieldRanked & ">" & rs.Fields(FieldRanked).Value, _
                CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
        Else
            rs1.Open "Select Count(*) as CountNum From (Select Distinct " & FieldRanked & " From " & TableRanked & " Where " & FieldRanked & ">=" & rs.Fields(FieldRanked).Value & ")", _
                CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
        End If
        rs.Fields(FieldResult).Value = rs1!CountNum.Value
        rs1.Close
        rs.MoveNext
    Loop
    rs.Close
End Sub

按下Ctrl+G,切換到立卽窗口,分彆輸入如下類似的代碼:

1 RankField "Score","Score","Rank1_VBA",true
2 RankField "Score","Score","Rank2_VBA",False

我們會得到如下類似的結果,Rank1_VBA列爲非連續排名結果,Rank2_VBA爲連續排名結果:


2、SQL查詢實現方式

相比於VBA代碼方式,在成績值髮生修改時,SQL查詢可以自動更新排名數據,而不需要像VBA過程要每次都手動重新運祘.

SELECT 
    Score.id, 
    Score.Score, 
    Score.Rank1_VBA, 
    Score.Rank2_VBA, 
    (Select Count(*)+1 From score AS Score_1 Where Score_1.Score>Score.Score) AS Rank1, 
    (Select Count(*)+1 From (Select Distinct Score_1.score From score AS Score_1) As tbl Where tbl.Score>Score.Score) AS Rank2
FROM Score;

創建這箇查詢後,會活的如下所示的運行結果:Rank1與Rank1_VBA對應,Rank2與Rank2_VBA對應.

    分享