/** Converts a call to an aggregate function to an expression. */ public SqlNode toSql(AggregateCall aggCall) { final SqlOperator op = aggCall.getAggregation(); final List<SqlNode> operandList = Expressions.list(); for (int arg : aggCall.getArgList()) { operandList.add(field(arg)); } final SqlLiteral qualifier = aggCall.isDistinct() ? SqlSelectKeyword.DISTINCT.symbol(POS) : null; final SqlNode[] operands = operandList.toArray(new SqlNode[0]); List<SqlNode> orderByList = Expressions.list(); for (RelFieldCollation field : aggCall.collation.getFieldCollations()) { addOrderItem(orderByList, field); } SqlNodeList orderList = new SqlNodeList(orderByList, POS); if (op instanceof SqlSumEmptyIsZeroAggFunction) { final SqlNode node = withOrder( SqlStdOperatorTable.SUM.createCall(qualifier, POS, operands), orderList); return SqlStdOperatorTable.COALESCE.createCall(POS, node, SqlLiteral.createExactNumeric("0", POS)); } else { return withOrder(op.createCall(qualifier, POS, operands), orderList); } }