Search in sources :

Example 1 with SqlSingleValueAggFunction

use of org.apache.calcite.sql.fun.SqlSingleValueAggFunction in project calcite by apache.

the class RelToSqlConverter method visit.

/**
 * @see #dispatch
 */
public Result visit(Aggregate e) {
    // "select a, b, sum(x) from ( ... ) group by a, b"
    final Result x = visitChild(0, e.getInput());
    final Builder builder;
    if (e.getInput() instanceof Project) {
        builder = x.builder(e);
        builder.clauses.add(Clause.GROUP_BY);
    } else {
        builder = x.builder(e, Clause.GROUP_BY);
    }
    List<SqlNode> groupByList = Expressions.list();
    final List<SqlNode> selectList = new ArrayList<>();
    for (int group : e.getGroupSet()) {
        final SqlNode field = builder.context.field(group);
        addSelect(selectList, field, e.getRowType());
        groupByList.add(field);
    }
    for (AggregateCall aggCall : e.getAggCallList()) {
        SqlNode aggCallSqlNode = builder.context.toSql(aggCall);
        if (aggCall.getAggregation() instanceof SqlSingleValueAggFunction) {
            aggCallSqlNode = dialect.rewriteSingleValueExpr(aggCallSqlNode);
        }
        addSelect(selectList, aggCallSqlNode, e.getRowType());
    }
    builder.setSelect(new SqlNodeList(selectList, POS));
    if (!groupByList.isEmpty() || e.getAggCallList().isEmpty()) {
        // Some databases don't support "GROUP BY ()". We can omit it as long
        // as there is at least one aggregate function.
        builder.setGroupBy(new SqlNodeList(groupByList, POS));
    }
    return builder.result();
}
Also used : AggregateCall(org.apache.calcite.rel.core.AggregateCall) Project(org.apache.calcite.rel.core.Project) ArrayList(java.util.ArrayList) SqlNodeList(org.apache.calcite.sql.SqlNodeList) SqlSingleValueAggFunction(org.apache.calcite.sql.fun.SqlSingleValueAggFunction) SqlNode(org.apache.calcite.sql.SqlNode)

Aggregations

ArrayList (java.util.ArrayList)1 AggregateCall (org.apache.calcite.rel.core.AggregateCall)1 Project (org.apache.calcite.rel.core.Project)1 SqlNode (org.apache.calcite.sql.SqlNode)1 SqlNodeList (org.apache.calcite.sql.SqlNodeList)1 SqlSingleValueAggFunction (org.apache.calcite.sql.fun.SqlSingleValueAggFunction)1