You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@flink.apache.org by ji...@apache.org on 2019/05/07 11:08:47 UTC

[flink] branch master updated: [FLINK-10976] [table] Add support for aggregate to table API This closes #8311.

This is an automated email from the ASF dual-hosted git repository.

jincheng pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/flink.git


The following commit(s) were added to refs/heads/master by this push:
     new 560b2bd  [FLINK-10976] [table] Add support for aggregate to table API This closes #8311.
560b2bd is described below

commit 560b2bd84f0f20def8b41c3c7b2c3dd3bc7cb2a8
Author: Dian Fu <fu...@alibaba-inc.com>
AuthorDate: Tue Dec 4 21:25:16 2018 +0800

    [FLINK-10976] [table] Add support for aggregate to table API
    This closes #8311.
---
 docs/dev/table/tableApi.md                         | 103 +++++++++++++++++
 .../apache/flink/table/api/AggregatedTable.java    |  64 +++++++++++
 .../org/apache/flink/table/api/GroupedTable.java   |  37 ++++++
 .../java/org/apache/flink/table/api/Table.java     |  39 ++++++-
 .../org/apache/flink/table/api/TableImpl.scala     |   8 +-
 .../org/apache/flink/table/api/tableImpl.scala     |  81 +++++++++++---
 .../table/operations/OperationTreeBuilder.scala    | 124 ++++++++++++++++++---
 .../table/api/stream/table/AggregateTest.scala     | 117 ++++++++++++++++++-
 .../stringexpr/AggregateStringExpressionTest.scala |  68 ++++++++++-
 .../table/validation/AggregateValidationTest.scala |  80 ++++++++++++-
 .../validation/TableAggregateValidationTest.scala  |  32 +++---
 .../runtime/stream/table/AggregateITCase.scala     |  42 +++++++
 .../table/utils/UserDefinedAggFunctions.scala      |  48 +++++++-
 13 files changed, 783 insertions(+), 60 deletions(-)

diff --git a/docs/dev/table/tableApi.md b/docs/dev/table/tableApi.md
index 5b3f1ca..71a0fa0 100644
--- a/docs/dev/table/tableApi.md
+++ b/docs/dev/table/tableApi.md
@@ -1970,6 +1970,62 @@ Table table = input
     
     <tr>
       <td>
+        <strong>Aggregate</strong><br>
+        <span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
+        <span class="label label-info">Result Updating</span>
+      </td>
+      <td>
+        <p>Performs an aggregate operation with an aggregate function. You have to close the "aggregate" with a select statement and the select statement does not support aggregate functions. The output of aggregate will be flattened if the output type is a composite type.</p>
+{% highlight java %}
+public class MyMinMaxAcc {
+    public int min = 0;
+    public int max = 0;
+}
+
+public class MyMinMax extends AggregateFunction<Row, MyMinMaxAcc> {
+
+    public void accumulate(MyMinMaxAcc acc, int value) {
+        if (value < acc.min) {
+            acc.min = value;
+        }
+        if (value > acc.max) {
+            acc.max = value;
+        }
+    }
+
+    @Override
+    public MyMinMaxAcc createAccumulator() {
+        return new MyMinMaxAcc();
+    }
+    
+    public void resetAccumulator(MyMinMaxAcc acc) {
+        acc.min = 0;
+        acc.max = 0;
+    }
+
+    @Override
+    public Row getValue(MyMinMaxAcc acc) {
+        return Row.of(acc.min, acc.max);
+    }
+
+    @Override
+    public TypeInformation<Row> getResultType() {
+        return new RowTypeInfo(Types.INT, Types.INT);
+    }
+}
+    
+AggregateFunction myAggFunc = new MyMinMax();
+tableEnv.registerFunction("myAggFunc", myAggFunc);
+Table table = input
+  .groupBy("key")
+  .aggregate("myAggFunc(a) as (x, y)")
+  .select("key, x, y")
+{% endhighlight %}
+      </td>
+    </tr>
+    
+    <tr>
+      <td>
         <strong>GroupBy TableAggregation</strong><br>
         <span class="label label-primary">Streaming</span><br>
         <span class="label label-info">Result Updating</span>
@@ -2091,6 +2147,53 @@ val table = input
     
     <tr>
       <td>
+        <strong>Aggregate</strong><br>
+        <span class="label label-primary">Batch</span> <span class="label label-primary">Streaming</span>
+        <span class="label label-info">Result Updating</span>
+      </td>
+      <td>
+        <p>Performs an aggregate operation with an aggregate function. You have to close the "aggregate" with a select statement and the select statement does not support aggregate functions. The output of aggregate will be flattened if the output type is a composite type.</p>
+{% highlight scala %}
+case class MyMinMaxAcc(var min: Int, var max: Int)
+
+class MyMinMax extends AggregateFunction[Row, MyMinMaxAcc] {
+
+  def accumulate(acc: MyMinMaxAcc, value: Int): Unit = {
+    if (value < acc.min) {
+      acc.min = value
+    }
+    if (value > acc.max) {
+      acc.max = value
+    }
+  }
+
+  override def createAccumulator(): MyMinMaxAcc = MyMinMaxAcc(0, 0)
+  
+  def resetAccumulator(acc: MyMinMaxAcc): Unit = {
+    acc.min = 0
+    acc.max = 0
+  }
+
+  override def getValue(acc: MyMinMaxAcc): Row = {
+    Row.of(Integer.valueOf(acc.min), Integer.valueOf(acc.max))
+  }
+
+  override def getResultType: TypeInformation[Row] = {
+    new RowTypeInfo(Types.INT, Types.INT)
+  }
+}
+
+val myAggFunc: AggregateFunction = new MyMinMax
+val table = input
+  .groupBy('key)
+  .aggregate(myAggFunc('a) as ('x, 'y))
+  .select('key, 'x, 'y)
+{% endhighlight %}
+      </td>
+    </tr>
+    
+    <tr>
+      <td>
         <strong>GroupBy TableAggregation</strong><br>
         <span class="label label-primary">Streaming</span><br>
         <span class="label label-info">Result Updating</span>
diff --git a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/AggregatedTable.java b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/AggregatedTable.java
new file mode 100644
index 0000000..44abb37
--- /dev/null
+++ b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/AggregatedTable.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.api;
+
+import org.apache.flink.annotation.PublicEvolving;
+import org.apache.flink.table.expressions.Expression;
+
+/**
+ * A table that has been performed on the aggregate function.
+ */
+@PublicEvolving
+public interface AggregatedTable {
+
+	/**
+	 * Performs a selection operation after an aggregate operation. The field expressions
+	 * cannot contain table functions and aggregations.
+	 *
+	 * <p>Example:
+	 *
+	 * <pre>
+	 * {@code
+	 *   AggregateFunction aggFunc = new MyAggregateFunction()
+	 *   tableEnv.registerFunction("aggFunc", aggFunc);
+	 *   table.groupBy("key")
+	 *     .aggregate("aggFunc(a, b) as (f0, f1, f2)")
+	 *     .select("key, f0, f1")
+	 * }
+	 * </pre>
+	 */
+	Table select(String fields);
+
+	/**
+	 * Performs a selection operation after an aggregate operation. The field expressions
+	 * cannot contain table functions and aggregations.
+	 *
+	 * <p>Scala Example:
+	 *
+	 * <pre>
+	 * {@code
+	 *   val aggFunc = new MyAggregateFunction
+	 *   table.groupBy('key)
+	 *     .aggregate(aggFunc('a, 'b) as ('f0, 'f1, 'f2))
+	 *     .select('key, 'f0, 'f1)
+	 * }
+	 * </pre>
+	 */
+	Table select(Expression... fields);
+}
diff --git a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/GroupedTable.java b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/GroupedTable.java
index 671964e..1b7c161 100644
--- a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/GroupedTable.java
+++ b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/GroupedTable.java
@@ -56,6 +56,43 @@ public interface GroupedTable {
 	Table select(Expression... fields);
 
 	/**
+	 * Performs an aggregate operation with an aggregate function. You have to close the
+	 * {@link #aggregate(String)} with a select statement. The output will be flattened if the
+	 * output type is a composite type.
+	 *
+	 * <p>Example:
+	 *
+	 * <pre>
+	 * {@code
+	 *   AggregateFunction aggFunc = new MyAggregateFunction()
+	 *   tableEnv.registerFunction("aggFunc", aggFunc);
+	 *   table.groupBy("key")
+	 *     .aggregate("aggFunc(a, b) as (f0, f1, f2)")
+	 *     .select("key, f0, f1")
+	 * }
+	 * </pre>
+	 */
+	AggregatedTable aggregate(String aggregateFunction);
+
+	/**
+	 * Performs an aggregate operation with an aggregate function. You have to close the
+	 * {@link #aggregate(Expression)} with a select statement. The output will be flattened if the
+	 * output type is a composite type.
+	 *
+	 * <p>Scala Example:
+	 *
+	 * <pre>
+	 * {@code
+	 *   val aggFunc = new MyAggregateFunction
+	 *   table.groupBy('key)
+	 *     .aggregate(aggFunc('a, 'b) as ('f0, 'f1, 'f2))
+	 *     .select('key, 'f0, 'f1)
+	 * }
+	 * </pre>
+	 */
+	AggregatedTable aggregate(Expression aggregateFunction);
+
+	/**
 	 * Performs a flatAggregate operation on a grouped table. FlatAggregate takes a
 	 * TableAggregateFunction which returns multiple rows. Use a selection after flatAggregate.
 	 *
diff --git a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Table.java b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Table.java
index 4b14f71..9f68e72 100644
--- a/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Table.java
+++ b/flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/Table.java
@@ -1060,6 +1060,41 @@ public interface Table {
 	Table flatMap(Expression tableFunction);
 
 	/**
+	 * Performs a global aggregate operation with an aggregate function. You have to close the
+	 * {@link #aggregate(String)} with a select statement. The output will be flattened if the
+	 * output type is a composite type.
+	 *
+	 * <p>Example:
+	 *
+	 * <pre>
+	 * {@code
+	 *   AggregateFunction aggFunc = new MyAggregateFunction()
+	 *   tableEnv.registerFunction("aggFunc", aggFunc);
+	 *   table.aggregate("aggFunc(a, b) as (f0, f1, f2)")
+	 *     .select("f0, f1")
+	 * }
+	 * </pre>
+	 */
+	AggregatedTable aggregate(String aggregateFunction);
+
+	/**
+	 * Performs a global aggregate operation with an aggregate function. You have to close the
+	 * {@link #aggregate(Expression)} with a select statement. The output will be flattened if the
+	 * output type is a composite type.
+	 *
+	 * <p>Scala Example:
+	 *
+	 * <pre>
+	 * {@code
+	 *   val aggFunc = new MyAggregateFunction
+	 *   table.aggregate(aggFunc('a, 'b) as ('f0, 'f1, 'f2))
+	 *     .select('f0, 'f1)
+	 * }
+	 * </pre>
+	 */
+	AggregatedTable aggregate(Expression aggregateFunction);
+
+	/**
 	 * Perform a global flatAggregate without groupBy. FlatAggregate takes a TableAggregateFunction
 	 * which returns multiple rows. Use a selection after the flatAggregate.
 	 *
@@ -1074,7 +1109,7 @@ public interface Table {
 	 * }
 	 * </pre>
 	 */
-	FlatAggregateTable flatAggregate(String tableAggFunction);
+	FlatAggregateTable flatAggregate(String tableAggregateFunction);
 
 	/**
 	 * Perform a global flatAggregate without groupBy. FlatAggregate takes a TableAggregateFunction
@@ -1090,5 +1125,5 @@ public interface Table {
 	 * }
 	 * </pre>
 	 */
-	FlatAggregateTable flatAggregate(Expression tableAggFunction);
+	FlatAggregateTable flatAggregate(Expression tableAggregateFunction);
 }
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/TableImpl.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/TableImpl.scala
index 7f67b66..99e9f3a 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/TableImpl.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/api/TableImpl.scala
@@ -205,7 +205,11 @@ class TableImpl(val tableEnv: TableEnvironment, relNode: RelNode) extends Table
 
   override def getTableOperation: TableOperation = ???
 
-  override def flatAggregate(tableAggFunction: String): FlatAggregateTable = ???
+  override def aggregate(aggregateFunction: String): AggregatedTable = ???
 
-  override def flatAggregate(tableAggFunction: Expression): FlatAggregateTable = ???
+  override def aggregate(aggregateFunction: Expression): AggregatedTable = ???
+
+  override def flatAggregate(tableAggregateFunction: String): FlatAggregateTable = ???
+
+  override def flatAggregate(tableAggregateFunction: Expression): FlatAggregateTable = ???
 }
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/api/tableImpl.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/api/tableImpl.scala
index d9b4cb6..0eff47a 100644
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/api/tableImpl.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/api/tableImpl.scala
@@ -445,12 +445,20 @@ class TableImpl(
     wrap(operationTreeBuilder.flatMap(tableFunction, operationTree))
   }
 
-  override def flatAggregate(tableAggFunction: String): FlatAggregateTable = {
-    groupBy().flatAggregate(tableAggFunction)
+  override def aggregate(aggregateFunction: String): AggregatedTable = {
+    aggregate(ExpressionParser.parseExpression(aggregateFunction))
   }
 
-  override def flatAggregate(tableAggFunction: Expression): FlatAggregateTable = {
-    groupBy().flatAggregate(tableAggFunction)
+  override def aggregate(aggregateFunction: Expression): AggregatedTable = {
+    groupBy().aggregate(aggregateFunction)
+  }
+
+  override def flatAggregate(tableAggregateFunction: String): FlatAggregateTable = {
+    groupBy().flatAggregate(tableAggregateFunction)
+  }
+
+  override def flatAggregate(tableAggregateFunction: Expression): FlatAggregateTable = {
+    groupBy().flatAggregate(tableAggregateFunction)
   }
 
   /**
@@ -503,19 +511,58 @@ class GroupedTableImpl(
       ))
   }
 
-  override def flatAggregate(tableAggFunction: String): FlatAggregateTable = {
-    flatAggregate(ExpressionParser.parseExpression(tableAggFunction))
+  override def aggregate(aggregateFunction: String): AggregatedTable = {
+    aggregate(ExpressionParser.parseExpression(aggregateFunction))
+  }
+
+  override def aggregate(aggregateFunction: Expression): AggregatedTable = {
+    new AggregatedTableImpl(table, groupKeys, aggregateFunction)
+  }
+
+  override def flatAggregate(tableAggregateFunction: String): FlatAggregateTable = {
+    flatAggregate(ExpressionParser.parseExpression(tableAggregateFunction))
+  }
+
+  override def flatAggregate(tableAggregateFunction: Expression): FlatAggregateTable = {
+    new FlatAggregateTableImpl(table, groupKeys, tableAggregateFunction)
+  }
+}
+
+/**
+  * The implementation of an [[AggregatedTable]] that has been performed on an aggregate function.
+  */
+class AggregatedTableImpl(
+    private[flink] val table: Table,
+    private[flink] val groupKeys: Seq[Expression],
+    private[flink] val aggregateFunction: Expression)
+  extends AggregatedTable {
+
+  private val tableImpl = table.asInstanceOf[TableImpl]
+
+  override def select(fields: String): Table = {
+    select(ExpressionParser.parseExpressionList(fields).asScala: _*)
   }
 
-  override def flatAggregate(tableAggFunction: Expression): FlatAggregateTable = {
-    new FlatAggregateTableImpl(table, groupKeys, tableAggFunction)
+  override def select(fields: Expression*): Table = {
+    new TableImpl(tableImpl.tableEnv,
+      tableImpl.operationTreeBuilder.project(fields,
+        tableImpl.operationTreeBuilder.aggregate(
+          groupKeys.asJava,
+          aggregateFunction,
+          tableImpl.operationTree
+        )
+      ))
   }
 }
 
+/**
+  * The implementation of an [[FlatAggregateTable]] that has been performed on an table aggregate
+  * function.
+  */
 class FlatAggregateTableImpl(
   private[flink] val table: Table,
   private[flink] val groupKey: Seq[Expression],
-  private[flink] val tableAggFunction: Expression) extends FlatAggregateTable {
+  private[flink] val tableAggregateFunction: Expression) extends FlatAggregateTable {
 
   private val tableImpl = table.asInstanceOf[TableImpl]
 
@@ -524,16 +571,14 @@ class FlatAggregateTableImpl(
   }
 
   override def select(fields: Expression*): Table = {
-    val resolvedTableAggFunction = tableAggFunction.accept(tableImpl.callResolver)
-
-    val flatAggTable = new TableImpl(tableImpl.tableEnv,
-      tableImpl.operationTreeBuilder.tableAggregate(
-        groupKey.asJava,
-        resolvedTableAggFunction,
-        tableImpl.operationTree
+    new TableImpl(tableImpl.tableEnv,
+      tableImpl.operationTreeBuilder.project(fields,
+        tableImpl.operationTreeBuilder.tableAggregate(
+          groupKey.asJava,
+          tableAggregateFunction.accept(tableImpl.callResolver),
+          tableImpl.operationTree
+        )
       ))
-
-    flatAggTable.select(fields: _*)
   }
 }
 
diff --git a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/operations/OperationTreeBuilder.scala b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/operations/OperationTreeBuilder.scala
index 197f519..6a6909b 100644
--- a/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/operations/OperationTreeBuilder.scala
+++ b/flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/operations/OperationTreeBuilder.scala
@@ -31,6 +31,7 @@ import org.apache.flink.table.expressions.lookups.TableReferenceLookup
 import org.apache.flink.table.functions.utils.UserDefinedFunctionUtils
 import org.apache.flink.table.operations.AliasOperationUtils.createAliasList
 import org.apache.flink.table.operations.JoinTableOperation.JoinType
+import org.apache.flink.table.operations.OperationExpressionsUtils.extractAggregationsAndProperties
 import org.apache.flink.table.operations.SetTableOperation.SetTableOperationType._
 import org.apache.flink.table.util.JavaScalaConversionUtil
 import org.apache.flink.table.util.JavaScalaConversionUtil.toScala
@@ -38,7 +39,7 @@ import org.apache.flink.util.Preconditions
 
 import _root_.scala.collection.JavaConversions._
 import _root_.scala.collection.JavaConverters._
-import _root_.scala.collection.mutable.ListBuffer
+import _root_.java.util.function.Supplier
 
 /**
   * Builder for [[[Operation]] tree.
@@ -97,14 +98,44 @@ class OperationTreeBuilder(private val tableEnv: TableEnvImpl) {
       explicitAlias: Boolean,
       overWindows: JList[OverWindow])
     : TableOperation = {
+
+    validateProjectList(projectList, overWindows)
+
     val resolver = resolverFor(tableCatalog, functionCatalog, child).withOverWindows(overWindows)
       .build
     val projections = resolver.resolve(projectList)
-
     projectionOperationFactory.create(projections, child, explicitAlias)
   }
 
   /**
+    * Window properties and aggregate function should not exist in the plain project, i.e., window
+    * properties should exist in the window operators and aggregate functions should exist in
+    * the aggregate operators.
+    */
+  private def validateProjectList(
+      projectList: JList[Expression],
+      overWindows: JList[OverWindow])
+    : Unit = {
+
+    val callResolver = new LookupCallResolver(tableEnv.functionCatalog)
+    val expressionsWithResolvedCalls = projectList.map(_.accept(callResolver)).asJava
+    val extracted = extractAggregationsAndProperties(
+      expressionsWithResolvedCalls,
+      new Supplier[String] {
+        override def get(): String = tableEnv.createUniqueAttributeName()
+      })
+    if (!extracted.getWindowProperties.isEmpty) {
+      throw new ValidationException("Window properties can only be used on windowed tables.")
+    }
+
+    // aggregate functions can't exist in the plain project except for the over window case
+    if (!extracted.getAggregations.isEmpty && overWindows.isEmpty) {
+      throw new ValidationException("Aggregate functions are not supported in the select right" +
+        " after the aggregate or flatAggregate operation.")
+    }
+  }
+
+  /**
     * Adds additional columns. Existing fields will be replaced if replaceIfExist is true.
     */
   def addColumns(
@@ -160,11 +191,64 @@ class OperationTreeBuilder(private val tableEnv: TableEnvImpl) {
     aggregateOperationFactory.createAggregate(resolvedGroupings, resolvedAggregates, child)
   }
 
+  /**
+    * Row based aggregate that will flatten the output if it is a composite type.
+    */
+  def aggregate(
+      groupingExpressions: JList[Expression],
+      aggregate: Expression,
+      child: TableOperation)
+    : TableOperation = {
+    // resolve for java string case, i.e., turn LookupCallExpression to CallExpression.
+    val resolvedAggregate = this.resolveExpression(aggregate, child)
+
+    // extract alias and aggregate function
+    var alias: Seq[String] = Seq()
+    val aggWithoutAlias = resolvedAggregate match {
+      case c: CallExpression
+        if c.getFunctionDefinition.getName == BuiltInFunctionDefinitions.AS.getName =>
+        alias = c.getChildren
+          .drop(1)
+          .map(e => e.asInstanceOf[ValueLiteralExpression].getValue.asInstanceOf[String])
+        c.getChildren.get(0)
+      case c: CallExpression
+        if c.getFunctionDefinition.isInstanceOf[AggregateFunctionDefinition] =>
+        if (alias.isEmpty) alias = UserDefinedFunctionUtils.getFieldInfo(
+          c.getFunctionDefinition.asInstanceOf[AggregateFunctionDefinition].getResultTypeInfo)._1
+        c
+      case e => e
+    }
+
+    // turn agg to a named agg, because it will be verified later.
+    var cnt = 0
+    val childNames = child.getTableSchema.getFieldNames
+    while (childNames.contains("TMP_" + cnt)) {
+      cnt += 1
+    }
+    val aggWithNamedAlias = new CallExpression(
+      BuiltInFunctionDefinitions.AS,
+      Seq(aggWithoutAlias, new ValueLiteralExpression("TMP_" + cnt, Types.STRING)))
+
+    // get agg table
+    val aggTableOperation = this.aggregate(groupingExpressions, Seq(aggWithNamedAlias), child)
+
+    // flatten the aggregate function
+    val aggNames = aggTableOperation.getTableSchema.getFieldNames
+    val flattenExpressions = aggNames.take(groupingExpressions.size())
+      .map(e => new UnresolvedReferenceExpression(e)) ++
+      Seq(new CallExpression(BuiltInFunctionDefinitions.FLATTEN,
+        Seq(new UnresolvedReferenceExpression(aggNames.last))))
+    val flattenedOperation = this.project(flattenExpressions.toList, aggTableOperation)
+
+    // add alias
+    aliasBackwardFields(flattenedOperation, alias)
+  }
+
   def tableAggregate(
-    groupingExpressions: JList[Expression],
-    tableAggFunction: Expression,
-    child: TableOperation)
-  : TableOperation = {
+      groupingExpressions: JList[Expression],
+      tableAggFunction: Expression,
+      child: TableOperation)
+    : TableOperation = {
 
     // Step1: add a default name to the call in the grouping expressions, e.g., groupBy(a % 5) to
     // groupBy(a % 5 as TMP_0). We need a name for every column so that to perform alias for the
@@ -196,15 +280,7 @@ class OperationTreeBuilder(private val tableEnv: TableEnvImpl) {
       .createAggregate(resolvedGroupings, Seq(resolvedFunctionAndAlias.f0), child)
 
     // Step4: add a top project to alias the output fields of the table aggregate.
-    val aliasName = resolvedFunctionAndAlias.f1
-    if (aliasName.nonEmpty) {
-      val namesBeforeAlias = tableAggOperation.getTableSchema.getFieldNames
-      val namesAfterAlias = namesBeforeAlias.dropRight(aliasName.size()) ++ aliasName
-      this.alias(namesAfterAlias.map(e =>
-        new UnresolvedReferenceExpression(e)).toList, tableAggOperation)
-    } else {
-      tableAggOperation
-    }
+    aliasBackwardFields(tableAggOperation, resolvedFunctionAndAlias.f1)
   }
 
   def windowAggregate(
@@ -420,6 +496,24 @@ class OperationTreeBuilder(private val tableEnv: TableEnvImpl) {
     resultName
   }
 
+  /**
+    * Rename backward fields of the input [[TableOperation]].
+    */
+  private def aliasBackwardFields(
+    inputOperation: TableOperation,
+    alias: Seq[String])
+  : TableOperation = {
+
+    if (alias.nonEmpty) {
+      val namesBeforeAlias = inputOperation.getTableSchema.getFieldNames
+      val namesAfterAlias = namesBeforeAlias.dropRight(alias.size()) ++ alias
+      this.alias(namesAfterAlias.map(e =>
+        new UnresolvedReferenceExpression(e)).toList, inputOperation)
+    } else {
+      inputOperation
+    }
+  }
+
   class NoWindowPropertyChecker(val exceptionMessage: String)
     extends ApiExpressionDefaultVisitor[Void] {
     override def visitCall(call: CallExpression): Void = {
diff --git a/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/AggregateTest.scala b/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/AggregateTest.scala
index 6eb0ddb..626306f 100644
--- a/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/AggregateTest.scala
+++ b/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/AggregateTest.scala
@@ -23,7 +23,7 @@ import org.apache.flink.api.scala._
 import org.apache.flink.table.api.{Session, Slide, Tumble}
 import org.apache.flink.table.api.scala._
 import org.apache.flink.table.runtime.utils.JavaUserDefinedAggFunctions.WeightedAvg
-import org.apache.flink.table.utils.TableTestBase
+import org.apache.flink.table.utils.{CountMinMax, TableTestBase}
 import org.apache.flink.table.utils.TableTestUtil._
 import org.junit.Test
 
@@ -313,4 +313,119 @@ class AggregateTest extends TableTestBase {
 
     util.verifyTable(result, expected)
   }
+
+  @Test
+  def testSimpleAggregate(): Unit = {
+    val util = streamTestUtil()
+    val table = util.addTable[(Int, Long, String)](
+      "MyTable", 'a, 'b, 'c)
+
+    val testAgg = new CountMinMax
+    val resultTable = table
+      .groupBy('b)
+      .aggregate(testAgg('a))
+      .select('b, 'f0, 'f1)
+
+    val expected =
+      unaryNode(
+        "DataStreamCalc",
+        unaryNode(
+          "DataStreamGroupAggregate",
+          unaryNode(
+            "DataStreamCalc",
+            streamTableNode(0),
+            term("select", "a", "b")
+          ),
+          term("groupBy", "b"),
+          term("select", "b", "CountMinMax(a) AS TMP_0")
+        ),
+        term("select", "b", "TMP_0.f0 AS f0", "TMP_0.f1 AS f1")
+      )
+    util.verifyTable(resultTable, expected)
+  }
+
+  @Test
+  def testSelectStar(): Unit = {
+    val util = streamTestUtil()
+    val table = util.addTable[(Int, Long, String)](
+      "MyTable", 'a, 'b, 'c)
+
+    val testAgg = new CountMinMax
+    val resultTable = table
+      .groupBy('b)
+      .aggregate(testAgg('a))
+      .select('*)
+
+    val expected =
+      unaryNode(
+        "DataStreamCalc",
+        unaryNode(
+          "DataStreamGroupAggregate",
+          unaryNode(
+            "DataStreamCalc",
+            streamTableNode(0),
+            term("select", "a", "b")
+          ),
+          term("groupBy", "b"),
+          term("select", "b", "CountMinMax(a) AS TMP_0")
+        ),
+        term("select", "b", "TMP_0.f0 AS f0", "TMP_0.f1 AS f1", "TMP_0.f2 AS f2")
+      )
+    util.verifyTable(resultTable, expected)
+  }
+
+  @Test
+  def testAggregateWithScalarResult(): Unit = {
+    val util = streamTestUtil()
+    val table = util.addTable[(Int, Long, String)](
+      "MyTable", 'a, 'b, 'c)
+
+    val resultTable = table
+      .groupBy('b)
+      .aggregate('a.count)
+      .select('b, 'TMP_0)
+
+    val expected =
+      unaryNode(
+        "DataStreamGroupAggregate",
+        unaryNode(
+          "DataStreamCalc",
+          streamTableNode(0),
+          term("select", "a", "b")
+        ),
+        term("groupBy", "b"),
+        term("select", "b", "COUNT(a) AS TMP_0")
+      )
+    util.verifyTable(resultTable, expected)
+  }
+
+  @Test
+  def testAggregateWithAlias(): Unit = {
+    val util = streamTestUtil()
+    val table = util.addTable[(Int, Long, String)](
+      "MyTable", 'a, 'b, 'c)
+
+    val testAgg = new CountMinMax
+    val resultTable = table
+      .groupBy('b)
+      .aggregate(testAgg('a) as ('x, 'y, 'z))
+      .select('b, 'x, 'y)
+
+    val expected =
+      unaryNode(
+        "DataStreamCalc",
+        unaryNode(
+          "DataStreamGroupAggregate",
+          unaryNode(
+            "DataStreamCalc",
+            streamTableNode(0),
+            term("select", "a", "b")
+          ),
+          term("groupBy", "b"),
+          term("select", "b", "CountMinMax(a) AS TMP_0")
+        ),
+        term("select", "b", "TMP_0.f0 AS x", "TMP_0.f1 AS y")
+      )
+    util.verifyTable(resultTable, expected)
+  }
 }
diff --git a/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/stringexpr/AggregateStringExpressionTest.scala b/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/stringexpr/AggregateStringExpressionTest.scala
index 63c7866..5ee4471 100644
--- a/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/stringexpr/AggregateStringExpressionTest.scala
+++ b/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/stringexpr/AggregateStringExpressionTest.scala
@@ -23,7 +23,7 @@ import org.apache.flink.table.api.Tumble
 import org.apache.flink.table.api.scala._
 import org.apache.flink.table.functions.aggfunctions.CountAggFunction
 import org.apache.flink.table.runtime.utils.JavaUserDefinedAggFunctions.{WeightedAvg, WeightedAvgWithMergeAndReset}
-import org.apache.flink.table.utils.TableTestBase
+import org.apache.flink.table.utils.{CountMinMax, TableTestBase}
 import org.junit.Test
 
 class AggregateStringExpressionTest extends TableTestBase {
@@ -169,6 +169,72 @@ class AggregateStringExpressionTest extends TableTestBase {
 
     verifyTableEquals(resJava, resScala)
   }
+
+  def testNonGroupedRowBasedAggregate(): Unit = {
+    val util = streamTestUtil()
+    val t = util.addTable[(Int, Long, String)]('a, 'b, 'c)
+
+    val testAgg = new CountMinMax
+    util.tableEnv.registerFunction("testAgg", testAgg)
+
+    // Expression / Scala API
+    val resScala = t
+      .aggregate(testAgg('a))
+      .select('f0, 'f1)
+
+    // String / Java API
+    val resJava = t
+      .aggregate("testAgg(a)")
+      .select("f0, f1")
+
+    verifyTableEquals(resScala, resJava)
+  }
+
+  @Test
+  def testGroupedRowBasedAggregate(): Unit = {
+    val util = streamTestUtil()
+    val t = util.addTable[(Int, Long, String)]('a, 'b, 'c)
+
+    val testAgg = new CountMinMax
+    util.tableEnv.registerFunction("testAgg", testAgg)
+
+    // Expression / Scala API
+    val resScala = t
+      .groupBy('b)
+      .aggregate(testAgg('a))
+      .select('b, 'f0, 'f1)
+
+    // String / Java API
+    val resJava = t
+      .groupBy("b")
+      .aggregate("testAgg(a)")
+      .select("b, f0, f1")
+
+    verifyTableEquals(resScala, resJava)
+  }
+
+  @Test
+  def testAggregateWithAlias(): Unit = {
+    val util = streamTestUtil()
+    val t = util.addTable[(Int, Long, String)]('a, 'b, 'c)
+
+    val testAgg = new CountMinMax
+    util.tableEnv.registerFunction("testAgg", testAgg)
+
+    // Expression / Scala API
+    val resScala = t
+      .groupBy('b)
+      .aggregate(testAgg('a) as ('x, 'y, 'z))
+      .select('b, 'x, 'y)
+
+    // String / Java API
+    val resJava = t
+      .groupBy("b")
+      .aggregate("testAgg(a) as (x, y, z)")
+      .select("b, x, y")
+
+    verifyTableEquals(resScala, resJava)
+  }
 }
 
 class TestPojo() {
diff --git a/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/validation/AggregateValidationTest.scala b/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/validation/AggregateValidationTest.scala
index 5953ca4..a8de009 100644
--- a/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/validation/AggregateValidationTest.scala
+++ b/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/validation/AggregateValidationTest.scala
@@ -19,9 +19,9 @@
 package org.apache.flink.table.api.stream.table.validation
 
 import org.apache.flink.api.scala._
-import org.apache.flink.table.api.ValidationException
+import org.apache.flink.table.api.{ExpressionParserException, ValidationException}
 import org.apache.flink.table.api.scala._
-import org.apache.flink.table.utils.TableTestBase
+import org.apache.flink.table.utils.{TableFunc0, TableTestBase}
 import org.junit.Test
 
 class AggregateValidationTest extends TableTestBase {
@@ -47,4 +47,80 @@ class AggregateValidationTest extends TableTestBase {
       // must fail. 'c is not a grouping key or aggregation
       .select('c)
   }
+
+  @Test(expected = classOf[ValidationException])
+  def testInvalidAggregationInSelection(): Unit = {
+    val util = streamTestUtil()
+    val table = util.addTable[(Long, Int, String)]('a, 'b, 'c)
+
+    table
+      .groupBy('a)
+      .aggregate('b.sum as 'd)
+      // must fail. Cannot use AggregateFunction in select right after aggregate
+      .select('d.sum)
+  }
+
+  @Test(expected = classOf[ValidationException])
+  def testInvalidWindowPropertiesInSelection(): Unit = {
+    val util = streamTestUtil()
+    val table = util.addTable[(Long, Int, String)]('a, 'b, 'c)
+
+    table
+      .groupBy('a)
+      .aggregate('b.sum as 'd)
+      // must fail. Cannot use window properties in select right after aggregate
+      .select('d.start)
+  }
+
+  @Test(expected = classOf[UnsupportedOperationException])
+  def testTableFunctionInSelection(): Unit = {
+    val util = streamTestUtil()
+    val table = util.addTable[(Long, Int, String)]('a, 'b, 'c)
+
+    util.tableEnv.registerFunction("func", new TableFunc0)
+    val resultTable = table
+      .groupBy('a)
+      .aggregate('b.sum as 'd)
+      // must fail. Cannot use TableFunction in select after aggregate
+      .select("func('abc')")
+
+    util.verifyTable(resultTable, "")
+  }
+
+  @Test(expected = classOf[ValidationException])
+  def testInvalidScalarFunctionInAggregate(): Unit = {
+    val util = streamTestUtil()
+    val table = util.addTable[(Long, Int, String)]('a, 'b, 'c)
+
+    table
+      .groupBy('a)
+      // must fail. Only AggregateFunction can be used in aggregate
+      .aggregate('c.upperCase as 'd)
+      .select('a, 'd)
+  }
+
+  @Test(expected = classOf[ValidationException])
+  def testInvalidTableFunctionInAggregate(): Unit = {
+    val util = streamTestUtil()
+    val table = util.addTable[(Long, Int, String)]('a, 'b, 'c)
+
+    util.tableEnv.registerFunction("func", new TableFunc0)
+    table
+      .groupBy('a)
+      // must fail. Only AggregateFunction can be used in aggregate
+      .aggregate("func(c) as d")
+      .select('a, 'd)
+  }
+
+  @Test(expected = classOf[ExpressionParserException])
+  def testMultipleAggregateExpressionInAggregate(): Unit = {
+    val util = streamTestUtil()
+    val table = util.addTable[(Long, Int, String)]('a, 'b, 'c)
+
+    util.tableEnv.registerFunction("func", new TableFunc0)
+    table
+      .groupBy('a)
+      // must fail. Only one AggregateFunction can be used in aggregate
+      .aggregate("sum(c), count(b)")
+  }
 }
diff --git a/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/validation/TableAggregateValidationTest.scala b/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/validation/TableAggregateValidationTest.scala
index 4ecca0e..9e5feb2 100644
--- a/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/validation/TableAggregateValidationTest.scala
+++ b/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/api/stream/table/validation/TableAggregateValidationTest.scala
@@ -79,6 +79,22 @@ class TableAggregateValidationTest extends TableTestBase {
   }
 
   @Test
+  def testInvalidWithAggregation(): Unit = {
+    expectedException.expect(classOf[ValidationException])
+    expectedException.expectMessage("Aggregate functions are not supported in the " +
+      "select right after the aggregate or flatAggregate operation.")
+
+    val util = streamTestUtil()
+    val table = util.addTable[(Long, Int, Timestamp)]('a, 'b, 'c)
+
+    val func = new EmptyTableAggFunc
+    table
+      .groupBy('b)
+      .flatAggregate(func('a, 'b) as ('x, 'y))
+      .select('x.count)
+  }
+
+  @Test
   def testInvalidParameterWithAgg(): Unit = {
     expectedException.expect(classOf[ValidationException])
     expectedException.expectMessage(
@@ -128,20 +144,4 @@ class TableAggregateValidationTest extends TableTestBase {
       .flatAggregate(func('a, 'b) as ('a, 'b))
       .select('*)
   }
-
-  @Test
-  def testInvalidDistinct(): Unit = {
-    expectedException.expect(classOf[ValidationException])
-    expectedException.expectMessage("A flatAggregate only accepts an expression which " +
-      "defines a table aggregate function that might be followed by some alias.")
-
-    val util = streamTestUtil()
-    val table = util.addTable[(Long, Int, Timestamp)]('a, 'b, 'c)
-
-    val func = new EmptyTableAggFunc
-    table
-      .groupBy('b)
-      .flatAggregate(func('a, 'b).distinct as ('a, 'b, 'c))
-      .select('a, 'b)
-  }
 }
diff --git a/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/runtime/stream/table/AggregateITCase.scala b/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/runtime/stream/table/AggregateITCase.scala
index c0a3e24..efb6c1b 100644
--- a/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/runtime/stream/table/AggregateITCase.scala
+++ b/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/runtime/stream/table/AggregateITCase.scala
@@ -27,6 +27,7 @@ import org.apache.flink.table.api.{StreamQueryConfig, Types}
 import org.apache.flink.table.runtime.utils.JavaUserDefinedAggFunctions.{CountDistinct, DataViewTestAgg, WeightedAvg}
 import org.apache.flink.table.runtime.utils.StreamITCase.RetractingSink
 import org.apache.flink.table.runtime.utils.{JavaUserDefinedAggFunctions, StreamITCase, StreamTestData, StreamingWithStateTestBase}
+import org.apache.flink.table.utils.CountMinMax
 import org.apache.flink.types.Row
 import org.junit.Assert.assertEquals
 import org.junit.Test
@@ -337,4 +338,45 @@ class AggregateITCase extends StreamingWithStateTestBase {
     val expected = List("(true,A,1)", "(true,B,2)", "(true,C,3)")
     assertEquals(expected.sorted, RowCollector.getAndClearValues.map(_.toString).sorted)
   }
+
+  @Test
+  def testNonGroupedAggregate(): Unit = {
+    val env = StreamExecutionEnvironment.getExecutionEnvironment
+    env.setStateBackend(getStateBackend)
+    val tEnv = StreamTableEnvironment.create(env)
+    StreamITCase.clear
+
+    val testAgg = new CountMinMax
+    val t = StreamTestData.get3TupleDataStream(env).toTable(tEnv, 'a, 'b, 'c)
+      .aggregate(testAgg('a))
+      .select('f0, 'f1, 'f2)
+
+    val results = t.toRetractStream[Row](queryConfig)
+    results.addSink(new StreamITCase.RetractingSink).setParallelism(1)
+    env.execute()
+
+    val expected = List("21,1,21")
+    assertEquals(expected.sorted, StreamITCase.retractedResults.sorted)
+  }
+
+  @Test
+  def testAggregate(): Unit = {
+    val env = StreamExecutionEnvironment.getExecutionEnvironment
+    env.setStateBackend(getStateBackend)
+    val tEnv = StreamTableEnvironment.create(env)
+    StreamITCase.clear
+
+    val testAgg = new CountMinMax
+    val t = StreamTestData.get3TupleDataStream(env).toTable(tEnv, 'a, 'b, 'c)
+      .groupBy('b)
+      .aggregate(testAgg('a))
+      .select('b, 'f0, 'f1, 'f2)
+
+    val results = t.toRetractStream[Row](queryConfig)
+    results.addSink(new StreamITCase.RetractingSink)
+    env.execute()
+
+    val expected = List("1,1,1,1", "2,2,2,3", "3,3,4,6", "4,4,7,10", "5,5,11,15", "6,6,16,21")
+    assertEquals(expected.sorted, StreamITCase.retractedResults.sorted)
+  }
 }
diff --git a/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/utils/UserDefinedAggFunctions.scala b/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/utils/UserDefinedAggFunctions.scala
index 14c8461..37a424d 100644
--- a/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/utils/UserDefinedAggFunctions.scala
+++ b/flink-table/flink-table-planner/src/test/scala/org/apache/flink/table/utils/UserDefinedAggFunctions.scala
@@ -20,13 +20,13 @@ package org.apache.flink.table.utils
 
 import org.apache.flink.table.functions.AggregateFunction
 import org.apache.flink.api.java.tuple.{Tuple2 => JTuple2}
-import java.lang.{Integer => JInt}
-import java.lang.{Float => JFloat}
+import java.lang.{Integer => JInt, Long => JLong, Float => JFloat}
 import java.util
 
 import org.apache.flink.api.common.typeinfo.TypeInformation
-import org.apache.flink.api.java.typeutils.{ObjectArrayTypeInfo, TupleTypeInfo}
+import org.apache.flink.api.java.typeutils.{ObjectArrayTypeInfo, RowTypeInfo, TupleTypeInfo}
 import org.apache.flink.table.api.Types
+import org.apache.flink.types.Row
 
 /**
   * User-defined aggregation function to compute the top 10 most visited Int IDs
@@ -143,3 +143,45 @@ class NonMergableCount extends AggregateFunction[Long, NonMergableCountAcc] {
 
   override def getValue(acc: NonMergableCountAcc): Long = acc.count
 }
+
+case class CountMinMaxAcc(var count: Long, var min: Int, var max: Int)
+
+class CountMinMax extends AggregateFunction[Row, CountMinMaxAcc] {
+
+  def accumulate(acc: CountMinMaxAcc, value: Int): Unit = {
+    if (acc.count == 0 || value < acc.min) {
+      acc.min = value
+    }
+    if (acc.count == 0 || value > acc.max) {
+      acc.max = value
+    }
+    acc.count += 1
+  }
+
+  def resetAccumulator(acc: CountMinMaxAcc): Unit = {
+    acc.count = 0
+    acc.min = 0
+    acc.max = 0
+  }
+
+  override def createAccumulator(): CountMinMaxAcc = CountMinMaxAcc(0L, 0, 0)
+
+  override def getValue(acc: CountMinMaxAcc): Row = {
+    val min: Int = if (acc.count > 0) {
+      acc.min
+    } else {
+      null.asInstanceOf[Int]
+    }
+
+    val max: Int = if (acc.count > 0) {
+      acc.max
+    } else {
+      null.asInstanceOf[Int]
+    }
+    Row.of(JLong.valueOf(acc.count), JInt.valueOf(min), JInt.valueOf(max))
+  }
+
+  override def getResultType: TypeInformation[Row] = {
+    new RowTypeInfo(Types.LONG, Types.INT, Types.INT)
+  }
+}