Crystal Reports 9 allows you to create a median summary field, but not to get the median for an array. Sure, you can get an average, or a mean, but not a median. If you want the median of a list of values, they must first be in order, which is outside the scope of this document (but there are other documents on sorting arrays.)
The Median is the middle value of a set by offset. For example, in the set (1, 3, 3, 4, 6) the median value is 3, while the average is 3.4. There are five elements; the middle element is then the third element. In the set (1, 3, 3, 4, 6, 6) the median value is slightly more difficult to calculate, because there are two middle values. In this case, the median is the average of the middle two values. The median of the set is 3 + 4 / 2 = 3.5, while the average is 3.83.
To find the middle number of an odd set, divide the number of elements by two, discarding the remainder, and add 1. For example, if there are five elements, 5/2 = 2 remainder 1/2. We drop the 1/2, add 1, and get the third element. In Crystal we can figure out if a number is even or odd using the remainder() function. If the remainder(NumberVar,2) is 1, then it was an odd number. If it's 0, then it's even.
Shared NumberVar Array foo;
Local NumberVar ArraySz := ubound(foo);
Local NumberVar Offset := 1;
Local StringVar OutString;
if ( remainder(ArraySz,2) ) = 1
then
(
Local NumberVar MedianValue := round(ArraySz/2) + 1;
foo [MedianValue];
) else (
Local NumberVar MedianValue := ( ArraySz/2 + ( ArraySz/2 + 1 ) ) / 2;
( foo [MedianValue] + foo [MedianValue + 1 ] ) / 2
)
In English: If the number is odd, then the median value is from the element represented by the size of the array, divided by two, remainder dropped, and one added. If it's even, then it's the number that's half the size of the array, plus the number after it in the array, divided by two.