Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

Aggregate Median (UDF)

From Wiki

Jump to: navigation, search

There is no Median in Jet SQL, unless it has been added for 2007, but here is an idea of how to get one. You will need ...

Some SQL ...

   SELECT Statistics.Month, Sum(([SentTo])) AS [Sum Sent], fMedian("Statistics","Month",[Month],"SentTo") AS [Median Sent]
   FROM Statistics
   GROUP BY Statistics.Month;


And a User Defined Function (UDF).

  1. Function fMedian(SQLOrTable, GroupFieldName, GroupFieldValue, MedianFieldName)
  2.     Dim rs As DAO.Recordset
  3.    
  4.     Set db = CurrentDb
  5.     Set rs1 = db.OpenRecordset(SQLOrTable, dbOpenDynaset)
  6.    
  7.     If IsDate(GroupFieldValue) Then
  8.         GroupFieldValue = "#" & GroupFieldValue & "#"
  9.     ElseIf Not IsNumeric(GroupFieldValue) Then
  10.         GroupFieldValue = "'" & Replace(GroupFieldValue, "'", "''") & "'"
  11.     End If
  12.    
  13.     rs1.Filter = GroupFieldName & "=" & GroupFieldValue
  14.     rs1.Sort = MedianFieldName
  15.    
  16.     Set rs = rs1.OpenRecordset()
  17.     rs.Move (rs.RecordCount / 2)
  18.    
  19.     If rs.RecordCount Mod 2 = 0 Then
  20.         varMedian1 = rs.Fields(MedianFieldName)
  21.         rs.MoveNext
  22.         fMedian = (varMedian1 + rs.Fields(MedianFieldName)) / 2
  23.     Else
  24.         fMedian = rs.Fields(MedianFieldName)
  25.     End If
  26.    
  27.     End Function

606 Rating: 2.9/5 (10 votes cast)