001    /*
002    // $Id: //open/mondrian/src/main/mondrian/olap/fun/MedianFunDef.java#5 $
003    // This software is subject to the terms of the Common Public License
004    // Agreement, available at the following URL:
005    // http://www.opensource.org/licenses/cpl.html.
006    // Copyright (C) 2006-2008 Julian Hyde
007    // All Rights Reserved.
008    // You must accept the terms of that agreement to use this software.
009    */
010    package mondrian.olap.fun;
011    
012    import mondrian.olap.FunDef;
013    import mondrian.olap.Evaluator;
014    import mondrian.olap.Dimension;
015    import mondrian.calc.Calc;
016    import mondrian.calc.ExpCompiler;
017    import mondrian.calc.ListCalc;
018    import mondrian.calc.impl.ValueCalc;
019    import mondrian.calc.impl.AbstractDoubleCalc;
020    import mondrian.mdx.ResolvedFunCall;
021    
022    import java.util.List;
023    
024    /**
025     * Definition of the <code>Median</code> MDX functions.
026     *
027     * @author jhyde
028     * @version $Id: //open/mondrian/src/main/mondrian/olap/fun/MedianFunDef.java#5 $
029     * @since Mar 23, 2006
030     */
031    class MedianFunDef extends AbstractAggregateFunDef {
032        static final ReflectiveMultiResolver Resolver = new ReflectiveMultiResolver(
033                "Median",
034                "Median(<Set>[, <Numeric Expression>])",
035                "Returns the median value of a numeric expression evaluated over a set.",
036                new String[]{"fnx", "fnxn"},
037                MedianFunDef.class);
038    
039        public MedianFunDef(FunDef dummyFunDef) {
040            super(dummyFunDef);
041        }
042    
043        public Calc compileCall(ResolvedFunCall call, ExpCompiler compiler) {
044            final ListCalc listCalc =
045                    compiler.compileList(call.getArg(0));
046            final Calc calc = call.getArgCount() > 1 ?
047                    compiler.compileScalar(call.getArg(1), true) :
048                    new ValueCalc(call);
049            return new AbstractDoubleCalc(call, new Calc[] {listCalc, calc}) {
050                public double evaluateDouble(Evaluator evaluator) {
051                    List memberList = evaluateCurrentList(listCalc, evaluator);
052                    return percentile(evaluator.push(), memberList, calc, 0.5);
053                }
054    
055                public boolean dependsOn(Dimension dimension) {
056                    return anyDependsButFirst(getCalcs(), dimension);
057                }
058            };
059        }
060    }
061    
062    // End MedianFunDef.java