AccessSQL实现连续及不连续Rank排名
⼀、关于起因
在Excel中我们经常使⽤Rank函数对数据进⾏排名操作。⽽在Access中我们要进⾏排名是不到这个Rank函数的,此时我们需要⾃⼰书写VBA代码或者建⽴SQL查询来完成排序操作。
今天我就来讲讲如何在Access中进⾏Rank排名操作,⾸先我给⼤家分析⼀下排名的种类跟实现⽅法。
⼆、排名的种类跟算法
现在学什么有前途1、⾮连续排名
逻辑算法:对于⼀组数列⾥的某个数字⽽⾔,其⾮连续排名是指:在该组数列⾥⽐该数字⼤的所有数字的个数+1
逻辑算法:
2、连续排名
逻辑算法:我想对您说五年级作文
逻辑算法:对于⼀组数列⾥的某个数字⽽⾔,其连续排名是指:在该组数列⾥⽐该数字⼤的所有⾮重复数字的个数+1
三、不同的实现⽅式
赵国的都城是⾸先我们做好准备⼯作,我们要建⽴必要表及其内部数据,如下图所⽰分别为表的结构及部分初始数据:
1、VBA实现⽅式
我写了⼀个Sub过程RankField,该过程的参数说明如下:
TableRanked:需排名的表名
FieldRanked:数据所在字段的字段名
FieldResult:排名后结果存储的字段名
NormalRank:是否是常规排名(True是常规排名,⾮连续排名,Excel中的Rank函数即为⾮连续排名;False为连续排名)
开个咖啡店要多少钱1Sub RankField(TableRanked As String, FieldRanked As String, FieldResult As String, NormalRank As Boolean)
2Dim rs As New ADODB.Recordset
3Dim rs1 As New ADODB.Recordset
4 rs.Open "Select " & FieldRanked & "," & FieldResult & " From " & TableRanked, CurrentProject.Connection, adOpenDynamic, adLockOptimistic
5Do Until rs.EOF
6If NormalRank Then
7 rs1.Open "Select Count(*)+1 as CountNum From " & TableRanked & " Where " & FieldRanked & ">" & rs.Fields(FieldRanked).Value, _
8 CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
9Else
10 rs1.Open "Select Count(*) as CountNum From (Select Distinct " & FieldRanked & " From " & TableRanked & " Where " & FieldRanked & ">=" & rs.Fields(FieldRanked).Value & ")", _
11 CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
12End If
13 rs.Fields(FieldResult).Value = rs1!CountNum.Value
14 rs1.Close谢霆锋张柏芝
15 rs.MoveNext
16Loop
17 rs.Close
18End 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过程要每次都⼿动重新运算.
1SELECT
2 Score.id,
3 Score.Score,
4 Score.Rank1_VBA,
5 Score.Rank2_VBA,
6 (Select Count(*)+1From score AS Score_1 Where Score_1.Score>Score.Score) AS Rank1,
神舟十三号返回直播
7 (Select Count(*)+1From (Select Distinct Score_1.score From score AS Score_1) As tbl Where tbl.Score>Score.Score) AS Rank2
8FROM Score;
创建这个查询后,会活的如下所⽰的运⾏结果:Rank1与Rank1_VBA对应,Rank2与Rank2_VBA对应.
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论