Java Code Examples for org.apache.calcite.sql.SqlAggFunction

The following examples show how to use org.apache.calcite.sql.SqlAggFunction. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: Bats   Source File: AggregateReduceFunctionsRule.java    License: Apache License 2.0 6 votes vote down vote up
private AggregateCall createAggregateCallWithBinding(
    RelDataTypeFactory typeFactory,
    SqlAggFunction aggFunction,
    RelDataType operandType,
    Aggregate oldAggRel,
    AggregateCall oldCall,
    int argOrdinal,
    int filter) {
  final Aggregate.AggCallBinding binding =
      new Aggregate.AggCallBinding(typeFactory, aggFunction,
          ImmutableList.of(operandType), oldAggRel.getGroupCount(),
          filter >= 0);
  return AggregateCall.create(aggFunction,
      oldCall.isDistinct(),
      oldCall.isApproximate(),
      ImmutableIntList.of(argOrdinal),
      filter,
      oldCall.collation,
      aggFunction.inferReturnType(binding),
      null);
}
 
Example 2
Source Project: dremio-oss   Source File: SqlImplementor.java    License: Apache License 2.0 6 votes vote down vote up
protected boolean hasNestedAggregations(LogicalAggregate rel) {
  List<AggregateCall> aggCallList = rel.getAggCallList();
  HashSet<Integer> aggregatesArgs = new HashSet<>();
  for (AggregateCall aggregateCall : aggCallList) {
    aggregatesArgs.addAll(aggregateCall.getArgList());
  }
  for (Integer aggregatesArg : aggregatesArgs) {
    SqlNode selectNode = ((SqlSelect) node).getSelectList().get(aggregatesArg);
    if (!(selectNode instanceof SqlBasicCall)) {
      continue;
    }
    for (SqlNode operand : ((SqlBasicCall) selectNode).getOperands()) {
      if (operand instanceof SqlCall) {
        final SqlOperator operator = ((SqlCall) operand).getOperator();
        if (operator instanceof SqlAggFunction) {
          return true;
        }
      }
    }
  }
  return false;
}
 
Example 3
Source Project: calcite   Source File: AggregateCall.java    License: Apache License 2.0 6 votes vote down vote up
/** Creates an AggregateCall, inferring its type if {@code type} is null. */
public static AggregateCall create(SqlAggFunction aggFunction,
    boolean distinct, boolean approximate, boolean ignoreNulls,
    List<Integer> argList, int filterArg, RelCollation collation,
    int groupCount,
    RelNode input, RelDataType type, String name) {
  if (type == null) {
    final RelDataTypeFactory typeFactory =
        input.getCluster().getTypeFactory();
    final List<RelDataType> types =
        SqlTypeUtil.projectTypes(input.getRowType(), argList);
    final Aggregate.AggCallBinding callBinding =
        new Aggregate.AggCallBinding(typeFactory, aggFunction, types,
            groupCount, filterArg >= 0);
    type = aggFunction.inferReturnType(callBinding);
  }
  return create(aggFunction, distinct, approximate, ignoreNulls, argList,
      filterArg, collation, type, name);
}
 
Example 4
Source Project: calcite   Source File: RelJsonReader.java    License: Apache License 2.0 6 votes vote down vote up
private AggregateCall toAggCall(RelInput relInput, Map<String, Object> jsonAggCall) {
  final Map<String, Object> aggMap = (Map) jsonAggCall.get("agg");
  final SqlAggFunction aggregation =
      relJson.toAggregation(aggMap);
  final Boolean distinct = (Boolean) jsonAggCall.get("distinct");
  @SuppressWarnings("unchecked")
  final List<Integer> operands = (List<Integer>) jsonAggCall.get("operands");
  final Integer filterOperand = (Integer) jsonAggCall.get("filter");
  final RelDataType type =
      relJson.toType(cluster.getTypeFactory(), jsonAggCall.get("type"));
  final String name = (String) jsonAggCall.get("name");
  return AggregateCall.create(aggregation, distinct, false, false, operands,
      filterOperand == null ? -1 : filterOperand,
      RelCollations.EMPTY,
      type, name);
}
 
Example 5
Source Project: flink   Source File: QueryOperationConverter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RelBuilder.AggCall visit(CallExpression call) {
	FunctionDefinition def = call.getFunctionDefinition();
	if (BuiltInFunctionDefinitions.DISTINCT == def) {
		Expression innerAgg = call.getChildren().get(0);
		return innerAgg.accept(new AggCallVisitor(relBuilder, expressionConverter, name, true));
	} else {
		SqlAggFunction sqlAggFunction = call.accept(sqlAggFunctionVisitor);
		return relBuilder.aggregateCall(
			sqlAggFunction,
			isDistinct,
			false,
			null,
			name,
			call.getChildren().stream().map(expr -> expr.accept(expressionConverter))
				.collect(Collectors.toList()));
	}
}
 
Example 6
Source Project: dremio-oss   Source File: DremioRelToSqlConverter.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a SqlWindow that adds ORDER BY if op is one of the given functions.
 */
protected static SqlWindow addDummyOrderBy(SqlWindow window, DremioContext
  context, SqlAggFunction op, List<SqlAggFunction> opsToAddClauseFor) {
  if (!SqlNodeList.isEmptyList(window.getOrderList())) {
    return window;
  }

  // Add the ORDER BY if op is one of the given functions.
  for (SqlAggFunction function : opsToAddClauseFor) {
    if (function == op) {
      SqlNodeList dummyOrderByList = new SqlNodeList(POS);
      dummyOrderByList.add(context.field(0));

      return SqlWindow.create(window.getDeclName(), window.getRefName(), window.getPartitionList(),
        dummyOrderByList, SqlLiteral.createBoolean(window.isRows(), POS), window.getLowerBound(),
        window.getUpperBound(), SqlLiteral.createBoolean(window.isAllowPartial(), POS), POS);
    }
  }

  return window;
}
 
Example 7
Source Project: calcite   Source File: AggregateCall.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates an AggregateCall.
 *
 * @param aggFunction Aggregate function
 * @param distinct    Whether distinct
 * @param approximate Whether approximate
 * @param argList     List of ordinals of arguments
 * @param filterArg   Ordinal of filter argument (the
 *                    {@code FILTER (WHERE ...)} clause in SQL), or -1
 * @param collation   How to sort values before aggregation (the
 *                    {@code WITHIN GROUP} clause in SQL)
 * @param type        Result type
 * @param name        Name (may be null)
 */
private AggregateCall(SqlAggFunction aggFunction, boolean distinct,
    boolean approximate, boolean ignoreNulls, List<Integer> argList,
    int filterArg, RelCollation collation, RelDataType type, String name) {
  this.type = Objects.requireNonNull(type);
  this.name = name;
  this.aggFunction = Objects.requireNonNull(aggFunction);
  this.argList = ImmutableList.copyOf(argList);
  this.filterArg = filterArg;
  this.collation = Objects.requireNonNull(collation);
  this.distinct = distinct;
  this.approximate = approximate;
  this.ignoreNulls = ignoreNulls;
  Preconditions.checkArgument(
      aggFunction.getDistinctOptionality() != Optionality.IGNORED || !distinct,
      "DISTINCT has no effect for this aggregate function, so must be false");
  Preconditions.checkArgument(filterArg < 0 || aggFunction.allowsFilter());
}
 
Example 8
Source Project: streamline   Source File: RelNodeCompiler.java    License: Apache License 2.0 6 votes vote down vote up
private void aggregate(AggregateCall call) {
  SqlAggFunction aggFunction = call.getAggregation();
  String aggregationName = call.getAggregation().getName();
  Type ty = typeFactory.getJavaClass(call.getType());
  if (call.getArgList().size() != 1) {
    if (aggregationName.equals("COUNT")) {
      if (call.getArgList().size() != 0) {
        throw new UnsupportedOperationException("Count with nullable fields");
      }
    }
  }
  if (aggFunction instanceof SqlUserDefinedAggFunction) {
    AggregateFunction aggregateFunction = ((SqlUserDefinedAggFunction) aggFunction).function;
    doAggregate((AggregateFunctionImpl) aggregateFunction, reserveAggVarName(call), ty, call.getArgList());
  } else {
    List<BuiltinAggregateFunctions.TypeClass> typeClasses = BuiltinAggregateFunctions.TABLE.get(aggregationName);
    if (typeClasses == null) {
      throw new UnsupportedOperationException(aggregationName + " Not implemented");
    }
    doAggregate(AggregateFunctionImpl.create(findMatchingClass(aggregationName, typeClasses, ty)),
                reserveAggVarName(call), ty, call.getArgList());
  }
}
 
Example 9
Source Project: Bats   Source File: RelBuilder.java    License: Apache License 2.0 6 votes vote down vote up
AggCallImpl(SqlAggFunction aggFunction, boolean distinct, boolean approximate, RexNode filter, String alias,
        ImmutableList<RexNode> operands, ImmutableList<RexNode> orderKeys) {
    this.aggFunction = Objects.requireNonNull(aggFunction);
    this.distinct = distinct;
    this.approximate = approximate;
    this.alias = alias;
    this.operands = Objects.requireNonNull(operands);
    this.orderKeys = Objects.requireNonNull(orderKeys);
    if (filter != null) {
        if (filter.getType().getSqlTypeName() != SqlTypeName.BOOLEAN) {
            throw RESOURCE.filterMustBeBoolean().ex();
        }
        if (filter.getType().isNullable()) {
            filter = call(SqlStdOperatorTable.IS_TRUE, filter);
        }
    }
    this.filter = filter;
}
 
Example 10
Source Project: calcite   Source File: SqlImplementor.java    License: Apache License 2.0 6 votes vote down vote up
private boolean hasNestedAggregations(Aggregate rel) {
  if (node instanceof SqlSelect) {
    final SqlNodeList selectList = ((SqlSelect) node).getSelectList();
    if (selectList != null) {
      final Set<Integer> aggregatesArgs = new HashSet<>();
      for (AggregateCall aggregateCall : rel.getAggCallList()) {
        aggregatesArgs.addAll(aggregateCall.getArgList());
      }
      for (int aggregatesArg : aggregatesArgs) {
        if (selectList.get(aggregatesArg) instanceof SqlBasicCall) {
          final SqlBasicCall call =
              (SqlBasicCall) selectList.get(aggregatesArg);
          for (SqlNode operand : call.getOperands()) {
            if (operand instanceof SqlCall
                && ((SqlCall) operand).getOperator() instanceof SqlAggFunction) {
              return true;
            }
          }
        }
      }
    }
  }
  return false;
}
 
Example 11
Source Project: flink   Source File: QueryOperationConverter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public RelBuilder.AggCall visit(CallExpression call) {
	FunctionDefinition def = call.getFunctionDefinition();
	if (BuiltInFunctionDefinitions.DISTINCT == def) {
		Expression innerAgg = call.getChildren().get(0);
		return innerAgg.accept(new AggCallVisitor(relBuilder, rexNodeConverter, name, true));
	} else {
		SqlAggFunction sqlAggFunction = call.accept(sqlAggFunctionVisitor);
		return relBuilder.aggregateCall(
			sqlAggFunction,
			isDistinct,
			false,
			null,
			name,
			call.getChildren().stream().map(expr -> expr.accept(rexNodeConverter))
				.collect(Collectors.toList()));
	}
}
 
Example 12
Source Project: calcite   Source File: RexUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns whether an array of exp contains no aggregate function calls whose
 * arguments are not {@link RexInputRef}s.
 *
 * @param exprs Expressions
 * @param litmus  Whether to assert if there is such a function call
 */
static boolean containNoNonTrivialAggs(List<RexNode> exprs, Litmus litmus) {
  for (RexNode expr : exprs) {
    if (expr instanceof RexCall) {
      RexCall rexCall = (RexCall) expr;
      if (rexCall.getOperator() instanceof SqlAggFunction) {
        for (RexNode operand : rexCall.operands) {
          if (!(operand instanceof RexLocalRef)
              && !(operand instanceof RexLiteral)) {
            return litmus.fail("contains non trivial agg: {}", operand);
          }
        }
      }
    }
  }
  return litmus.succeed();
}
 
Example 13
Source Project: dremio-oss   Source File: OverUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Indicates if the given OVER clause has a window frame that is automatically added by
 * Calcite if the frame is not specified.
 */
public static boolean hasDefaultFrame(SqlAggFunction operator, boolean isRows, RexWindowBound lowerBound, RexWindowBound upperBound, int oerderKeyCount) {
  // When Calcite parses an OVER clause with no frame,
  // it inject a 'default' frame depending on the function.
  // 1. For ROW_NUMBER(), it generates ROWS UNBOUNDED PRECEDING and CURRENT ROW.
  // 2. For others, it generates RANGE UNBOUNDED PRECEDING and UNBOUNDED FOLLOWING if unsorted.
  // 3. If it's not ROW_NUMBER(), and it is sorted, Calcite uses RANGE UNBOUNDED PRECEDING AND CURRENT ROW
  // Adding these unnecessary frames cause some RDBMSes (eg SQL Server) to fail.
  //
  // This code happens in SqlToRelConverter.convertOver(), SqlValidatorImpl.resolveWindow(),
  // and SqlWindow.create()/SqlWindow.populateBounds().

  return // Note: intentionally not simplifying this boolean for clarity.
    (operator == SqlStdOperatorTable.ROW_NUMBER && isRows &&
      lowerBound.isUnbounded() && lowerBound.isPreceding() &&
      upperBound.isCurrentRow()) // First condition.
      ||
      (!isRows && (oerderKeyCount == 0) &&
        lowerBound.isUnbounded() && lowerBound.isPreceding() &&
        upperBound.isUnbounded() && upperBound.isFollowing()) // Second condition.
      ||
      (!isRows && //(oerderKeyCount != 0) &&
        lowerBound.isUnbounded() && lowerBound.isPreceding() &&
        !upperBound.isUnbounded() && upperBound.isCurrentRow()); // Third condition.
}
 
Example 14
Source Project: Bats   Source File: LatticeSuggester.java    License: Apache License 2.0 5 votes vote down vote up
private MutableMeasure(SqlAggFunction aggregate, boolean distinct,
    List<ColRef> arguments, String name) {
  this.aggregate = aggregate;
  this.arguments = arguments;
  this.distinct = distinct;
  this.name = name;
}
 
Example 15
Source Project: flink   Source File: QueryOperationConverter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RelBuilder.AggCall visit(CallExpression call) {
	SqlAggFunction sqlAggFunction = call.accept(sqlAggFunctionVisitor);
	return relBuilder.aggregateCall(
		sqlAggFunction,
		false,
		false,
		null,
		sqlAggFunction.toString(),
		call.getChildren().stream().map(expr -> expr.accept(expressionConverter)).collect(toList()));
}
 
Example 16
Source Project: kylin   Source File: OLAPAggregateRel.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
private AggregateCall rewriteAggregateCall(AggregateCall aggCall, FunctionDesc func) {
    // rebuild function
    String callName = getSqlFuncName(aggCall);
    RelDataType fieldType = aggCall.getType();
    SqlAggFunction newAgg = aggCall.getAggregation();

    Map<String, Class<?>> udafMap = func.getMeasureType().getRewriteCalciteAggrFunctions();
    if (func.isCount()) {
        newAgg = SqlStdOperatorTable.SUM0;
    } else if (udafMap != null && udafMap.containsKey(callName)) {
        newAgg = createCustomAggFunction(callName, fieldType, udafMap.get(callName));
    }

    // rebuild parameters
    List<Integer> newArgList = Lists.newArrayList(aggCall.getArgList());
    if (udafMap != null && udafMap.containsKey(callName)) {
        newArgList = truncArgList(newArgList, udafMap.get(callName));
    }
    if (func.needRewriteField()) {
        RelDataTypeField field = getInput().getRowType().getField(func.getRewriteFieldName(), true, false);
        if (newArgList.isEmpty()) {
            newArgList.add(field.getIndex());
        } else {
            // TODO: only the first column got overwritten
            newArgList.set(0, field.getIndex());
        }
    }

    // rebuild aggregate call
    AggregateCall newAggCall = new AggregateCall(newAgg, false, newArgList, fieldType, callName);

    return newAggCall;
}
 
Example 17
Source Project: Bats   Source File: AbstractMaterializedViewRule.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get rollup aggregation function.
 */
protected SqlAggFunction getRollup(SqlAggFunction aggregation) {
    if (aggregation == SqlStdOperatorTable.SUM || aggregation == SqlStdOperatorTable.MIN
            || aggregation == SqlStdOperatorTable.MAX || aggregation == SqlStdOperatorTable.SUM0
            || aggregation == SqlStdOperatorTable.ANY_VALUE) {
        return aggregation;
    } else if (aggregation == SqlStdOperatorTable.COUNT) {
        return SqlStdOperatorTable.SUM0;
    } else {
        return null;
    }
}
 
Example 18
Source Project: calcite   Source File: PigRelOpVisitor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Builds a window function for {@link LORank}.
 *
 * @param loRank Pig logical rank operator
 * @return The window function
 * @throws FrontendException Exception during processing Pig operator
 */
private RexNode buildRankField(LORank loRank) throws FrontendException {
  // Aggregate function is either RANK or DENSE_RANK
  SqlAggFunction rank =
      loRank.isDenseRank() ? SqlStdOperatorTable.DENSE_RANK : SqlStdOperatorTable.RANK;

  // Build the order keys
  List<RexFieldCollation> orderNodes = new ArrayList<>();
  for (int i = 0; i < loRank.getRankColPlans().size(); i++) {
    RexNode orderNode =
        PigRelExVisitor.translatePigEx(builder, loRank.getRankColPlans().get(i));
    Set<SqlKind> flags = new HashSet<>();
    if (!loRank.getAscendingCol().get(i)) {
      flags.add(SqlKind.DESCENDING);
    }
    orderNodes.add(new RexFieldCollation(orderNode, flags));
  }

  return builder.getRexBuilder().makeOver(
      PigTypes.TYPE_FACTORY.createSqlType(SqlTypeName.BIGINT), // Return type
      rank, // Aggregate function
      Collections.emptyList(), // Operands for the aggregate function, empty here
      Collections.emptyList(), // No partition keys
      ImmutableList.copyOf(orderNodes), // order keys
      RexWindowBounds.UNBOUNDED_PRECEDING,
      RexWindowBounds.CURRENT_ROW,
      false, // Range-based
      true, // allow partial
      false, // not return null when count is zero
      false, // no distinct
      false);
}
 
Example 19
Source Project: Bats   Source File: SqlImplementor.java    License: Apache License 2.0 5 votes vote down vote up
private SqlCall createOverCall(SqlAggFunction op, List<SqlNode> operands, SqlWindow window) {
    if (op instanceof SqlSumEmptyIsZeroAggFunction) {
        // Rewrite "SUM0(x) OVER w" to "COALESCE(SUM(x) OVER w, 0)"
        final SqlCall node = createOverCall(SqlStdOperatorTable.SUM, operands, window);
        return SqlStdOperatorTable.COALESCE.createCall(POS, node, SqlLiteral.createExactNumeric("0", POS));
    }
    final SqlCall aggFunctionCall = op.createCall(POS, operands);
    return SqlStdOperatorTable.OVER.createCall(POS, aggFunctionCall, window);
}
 
Example 20
Source Project: Bats   Source File: AggregateCall.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an AggregateCall.
 *
 * @param aggFunction Aggregate function
 * @param distinct    Whether distinct
 * @param argList     List of ordinals of arguments
 * @param type        Result type
 * @param name        Name (may be null)
 */
@Deprecated // to be removed before 2.0
public AggregateCall(
    SqlAggFunction aggFunction,
    boolean distinct,
    List<Integer> argList,
    RelDataType type,
    String name) {
  this(aggFunction, distinct, false,
      argList, -1, RelCollations.EMPTY, type, name);
}
 
Example 21
Source Project: calcite   Source File: AggregateStarTableRule.java    License: Apache License 2.0 5 votes vote down vote up
private static int find(ImmutableList<Lattice.Measure> measures,
    Pair<SqlAggFunction, List<Integer>> seek) {
  for (int i = 0; i < measures.size(); i++) {
    Lattice.Measure measure = measures.get(i);
    if (measure.agg.equals(seek.left)
        && measure.argOrdinals().equals(seek.right)) {
      return i;
    }
  }
  return -1;
}
 
Example 22
Source Project: Bats   Source File: AggregateCall.java    License: Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public static AggregateCall create(SqlAggFunction aggFunction,
    boolean distinct, List<Integer> argList, int groupCount, RelNode input,
    RelDataType type, String name) {
  return create(aggFunction, distinct, false, argList, -1,
      RelCollations.EMPTY, groupCount, input, type, name);
}
 
Example 23
Source Project: Bats   Source File: AggregateCall.java    License: Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public static AggregateCall create(SqlAggFunction aggFunction,
    boolean distinct, List<Integer> argList, int filterArg, int groupCount,
    RelNode input, RelDataType type, String name) {
  return create(aggFunction, distinct, false, argList, filterArg,
      RelCollations.EMPTY, groupCount, input, type, name);
}
 
Example 24
Source Project: Bats   Source File: AggregateCall.java    License: Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public static AggregateCall create(SqlAggFunction aggFunction,
    boolean distinct, boolean approximate, List<Integer> argList,
    int filterArg, int groupCount,
    RelNode input, RelDataType type, String name) {
  return create(aggFunction, distinct, approximate, argList,
      filterArg, RelCollations.EMPTY, groupCount, input, type, name);
}
 
Example 25
Source Project: calcite   Source File: RexBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public RexNode makeOver(RelDataType type, SqlAggFunction operator,
    List<RexNode> exprs, List<RexNode> partitionKeys,
    ImmutableList<RexFieldCollation> orderKeys,
    RexWindowBound lowerBound, RexWindowBound upperBound,
    boolean rows, boolean allowPartial, boolean nullWhenCountZero,
    boolean distinct) {
  return makeOver(type, operator, exprs, partitionKeys, orderKeys, lowerBound,
      upperBound, rows, allowPartial, nullWhenCountZero, distinct, false);
}
 
Example 26
Source Project: calcite   Source File: Lattice.java    License: Apache License 2.0 5 votes vote down vote up
private SqlAggFunction resolveAgg(String aggName) {
  if (aggName.equalsIgnoreCase("count")) {
    return SqlStdOperatorTable.COUNT;
  } else if (aggName.equalsIgnoreCase("sum")) {
    return SqlStdOperatorTable.SUM;
  } else {
    throw new RuntimeException("Unknown lattice aggregate function "
        + aggName);
  }
}
 
Example 27
Source Project: Bats   Source File: SubstitutionVisitor.java    License: Apache License 2.0 5 votes vote down vote up
public static SqlAggFunction getRollup(SqlAggFunction aggregation) {
    if (aggregation == SqlStdOperatorTable.SUM || aggregation == SqlStdOperatorTable.MIN
            || aggregation == SqlStdOperatorTable.MAX || aggregation == SqlStdOperatorTable.SUM0
            || aggregation == SqlStdOperatorTable.ANY_VALUE) {
        return aggregation;
    } else if (aggregation == SqlStdOperatorTable.COUNT) {
        return SqlStdOperatorTable.SUM0;
    } else {
        return null;
    }
}
 
Example 28
Source Project: calcite   Source File: MongoAggregate.java    License: Apache License 2.0 5 votes vote down vote up
private String toMongo(SqlAggFunction aggregation, List<String> inNames,
    List<Integer> args) {
  if (aggregation == SqlStdOperatorTable.COUNT) {
    if (args.size() == 0) {
      return "{$sum: 1}";
    } else {
      assert args.size() == 1;
      final String inName = inNames.get(args.get(0));
      return "{$sum: {$cond: [ {$eq: ["
          + MongoRules.quote(inName)
          + ", null]}, 0, 1]}}";
    }
  } else if (aggregation instanceof SqlSumAggFunction
      || aggregation instanceof SqlSumEmptyIsZeroAggFunction) {
    assert args.size() == 1;
    final String inName = inNames.get(args.get(0));
    return "{$sum: " + MongoRules.maybeQuote("$" + inName) + "}";
  } else if (aggregation == SqlStdOperatorTable.MIN) {
    assert args.size() == 1;
    final String inName = inNames.get(args.get(0));
    return "{$min: " + MongoRules.maybeQuote("$" + inName) + "}";
  } else if (aggregation == SqlStdOperatorTable.MAX) {
    assert args.size() == 1;
    final String inName = inNames.get(args.get(0));
    return "{$max: " + MongoRules.maybeQuote("$" + inName) + "}";
  } else if (aggregation == SqlStdOperatorTable.AVG) {
    assert args.size() == 1;
    final String inName = inNames.get(args.get(0));
    return "{$avg: " + MongoRules.maybeQuote("$" + inName) + "}";
  } else {
    throw new AssertionError("unknown aggregate " + aggregation);
  }
}
 
Example 29
Source Project: calcite   Source File: SubstitutionVisitor.java    License: Apache License 2.0 5 votes vote down vote up
public static SqlAggFunction getRollup(SqlAggFunction aggregation) {
  if (aggregation == SqlStdOperatorTable.SUM
      || aggregation == SqlStdOperatorTable.MIN
      || aggregation == SqlStdOperatorTable.MAX
      || aggregation == SqlStdOperatorTable.SUM0
      || aggregation == SqlStdOperatorTable.ANY_VALUE) {
    return aggregation;
  } else if (aggregation == SqlStdOperatorTable.COUNT) {
    return SqlStdOperatorTable.SUM0;
  } else {
    return null;
  }
}
 
Example 30
Source Project: kylin   Source File: OLAPAggregateRule.java    License: Apache License 2.0 5 votes vote down vote up
private boolean containsAvg(LogicalAggregate agg) {
    for (AggregateCall call : agg.getAggCallList()) {
        SqlAggFunction func = call.getAggregation();
        if (func instanceof SqlAvgAggFunction)
            return true;
    }
    return false;
}