I've never had to find the Median of a range of numbers in a project until this past week. I first looked to see if there were any functions that will perform this task more quickly (and none exist in VBscript), and I also checked if any exist in SQL Server. Now if you're running SQL Server 2012 or later then there is a function called PERCENTILE_DISC but we currently run on 2008 R2.
So, I wrote a simple script that will get the job done (some of the ones I found online were more complex than needed to be). Note, this is in VBScript but you can use the logic and change the syntax based on whatever language you're using.
'FIRST PUT YOUR VALUES IN A STRING (YOU MIGHT HAVE TO READ THIS IN FROM THE DATABASE
Dim aryValues : aryValues = "107, 105, 104, 102, 102, 102, 101, 99, 99, 99, 98, 97, 97, 97, 95, 94, 93"
aryValues = split(aryValues,",")
Dim aryCount : aryCount = ubound(aryValues) + 1 'NUMBER OF VALUES IN OUR STRING
Dim MiddleCount : MiddleCount = aryCount / 2 'DIVIDE THE NUMBER BY 2 TO GET THE MIDDLE VALUE
if inStr(MiddleCount,".5") then 'Count is ODD
MiddleCount = cint(replace(MiddleCount,".5",""))
else 'Count is Even
'WHEN THERE'S AN EVEN AMOUNT OF NUMBERS YOU AVERAGE THE 2 MIDDLE NUMBERS
vMedian = ( cint(aryValues(MiddleCount-1)) + aryValues(MiddleCount) ) / 2
end if
Comments
Post a Comment