median

# Thread: median

1. Senior Member
Join Date
Dec 1969
Posts
188

## median

I have 3 numbers - 1,2 and 3. how do I get median(answer is 2). I know there is a function in VB called median. What function to use in VBscript.<BR><BR>Thanks

2. 12OzCoffeeCup Guest

## RE: median

Is this a trick question? I know the answer, hold on... 5! no wait... ohhh!... no that&#039s not it....

3. Senior Member
Join Date
Dec 1969
Posts
96,118

## RE: median

Sorry, but you&#039ll have to write your own if you want to use VBScript. <BR><BR>*Average* is, of course, trivial to write. If you are willing to live with average, instead of median, you could write it in 30 seconds or so.<BR><BR>But to do median, the only practical way is to sort the array first and then find the element at (or closest to) the midpoint. And, guess what, VBScript *also* does not have a builtin sort function. So you get to write your own sort.<BR><BR>[ For those who don&#039t know:<BR><BR>The average of 1,1,1,2,100 is 21 (sum is 105, divided by 5 gives 21).<BR><BR>The median of 1,1,1,2,100 is 1. Because there are the same *number* of values both &#060;= 1 and &#062;= 1.<BR><BR>Note that the order doesn&#039t matter. The average of 2,1,100,1,1 is still 21. The median of 2,1,100,1,1 is still 1.<BR><BR>Very different concepts.<BR><BR><BR>

4. Senior Member
Join Date
Dec 1969
Posts
626

## RE: median

Why not write your own function?<BR>

5. Senior Member
Join Date
Dec 1969
Posts
96,118

## Median actually easy with a DB!

&#062; Why not write your own function?<BR><BR>Probably because it means doing a sort of the array, and (lets face it) most VBS people don&#039t know how to write a sort.<BR><BR>HOWEVER...<BR><BR>I just realized that this is the "Databases" message board. *IF* you are getting the data from a database, why not let the DB do the sort? Then getting the median is easy!<BR><BR>Something like this:<BR><BR>&#060;%<BR>SQL = "SELECT salary FROM employees ORDER BY salary"<BR>Set RS = someConnection.Execute(SQL)<BR>rows = RS.GetRows<BR>median = rows( 0, UBound(rows,2) 2 )<BR>RS.Close<BR>%&#062;<BR><BR>See it? You just get the desired field into an array (it&#039s always doubly dimensioned, becuz that&#039s how GetRows worked, but if you are only getting one field then the first dimension is always 0 [one element]) and the get the middle element of the array. Presto.<BR><BR><BR> <BR>

6. Senior Member
Join Date
Dec 1969
Posts
626

## RE: Median actually easy with a DB!

fast and easy ... nice solution.

7. Senior Member
Join Date
Dec 1969
Posts
188

## Thanks Bill! I will try this

thanks

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•