|
[刷一下存在感]做一个自定义函数,再建一个查询就可以了,没那么复杂:
Public Function GetMidVal(groupVal, sDate As Date, eDate As Date) As Variant
'返回中位数
'groupVal:分组字段的某个值
'sDate:指定统计期间的开始日期
'eDate:指定统计期间的结束日期
Dim Rec As New ADODB.Recordset
Dim i As Long, N1, N2
'按照条件查询记录集
Rec.Open "select * from data where 商品ID='" & groupVal & "' and 日期 between #" & sDate & "# and #" & eDate & "# order by 销量", CurrentProject.Connection, adOpenKeyset, adLockReadOnly
Select Case Rec.RecordCount
Case Is > 1 '统计期间有销售记录
If Rec.RecordCount Mod 2 = 0 Then '记录数为偶数
For i = 1 To Int(Rec.RecordCount / 2) - 1 '把指针移动到记录集正中间偏上的位置
Rec.MoveNext
Next i
N1 = Rec.Fields("销量") '
Rec.MoveNext '把指针移动到记录集中间偏下的位置
N2 = Rec.Fields("销量")
GetMidVal = (N1 + N2) / 2 '获得平均值
Else '记录数为奇数
For i = 1 To 1 + Int(Rec.RecordCount / 2) '把指针移动到记录集的中间
Rec.MoveNext
Next i
GetMidVal = Rec.Fields("销量")
End If
Case 1
GetMidVal = Rec.Fields("销量")
Case 0 '统计期间没有销售记录
GetMidVal = 0
End Select
End Function
查询SQL:
SELECT data.商品ID, GetMidVal([商品ID],#3/3/2021#,#4/2/2021#) AS 中位数 FROM data GROUP BY data.商品ID
|
|