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

[flink] branch master updated: [FLINK-12081][table-planner-blink] Introduce aggregation operator code generator to blink batch

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

kurt 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 518cf6a  [FLINK-12081][table-planner-blink] Introduce aggregation operator code generator to blink batch
518cf6a is described below

commit 518cf6a10ba105d655de738ce5fccc5fffc8e8a6
Author: JingsongLi <lz...@aliyun.com>
AuthorDate: Wed Mar 27 19:22:12 2019 +0800

    [FLINK-12081][table-planner-blink] Introduce aggregation operator code generator to blink batch
    
    This closes #8099
---
 .../flink/table/expressions/RexNodeConverter.java  |  22 +-
 .../apache/flink/table/codegen/CodeGenUtils.scala  |   8 +
 .../flink/table/codegen/CodeGeneratorContext.scala |   8 +-
 .../codegen/agg/AggsHandlerCodeGenerator.scala     |  36 +-
 .../table/codegen/agg/batch/AggCodeGenHelper.scala | 723 +++++++++++++++++
 .../agg/batch/AggWithoutKeysCodeGenerator.scala    | 120 +++
 .../codegen/agg/batch/HashAggCodeGenHelper.scala   | 860 +++++++++++++++++++++
 .../codegen/agg/batch/HashAggCodeGenerator.scala   | 239 ++++++
 .../codegen/agg/batch/SortAggCodeGenerator.scala   | 151 ++++
 .../flink/table/codegen/agg/TestLongAvgFunc.java   |   2 +-
 .../apache/flink/table/util/BaseRowTestUtil.java   |  13 +-
 .../flink/table/codegen/agg/AggTestBase.scala      | 101 +++
 .../codegen/agg/AggsHandlerCodeGeneratorTest.scala |  82 +-
 .../codegen/agg/batch/AggWithoutKeysTest.scala     | 105 +++
 .../table/codegen/agg/batch/BatchAggTestBase.scala | 103 +++
 .../agg/batch/HashAggCodeGeneratorTest.scala       | 132 ++++
 .../agg/batch/SortAggCodeGeneratorTest.scala       | 121 +++
 .../table/runtime/OneInputOperatorWrapper.java     |   6 +
 18 files changed, 2724 insertions(+), 108 deletions(-)

diff --git a/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/expressions/RexNodeConverter.java b/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/expressions/RexNodeConverter.java
index 35c8868..bdf1c01 100644
--- a/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/expressions/RexNodeConverter.java
+++ b/flink-table/flink-table-planner-blink/src/main/java/org/apache/flink/table/expressions/RexNodeConverter.java
@@ -21,6 +21,7 @@ package org.apache.flink.table.expressions;
 import org.apache.flink.table.calcite.FlinkTypeFactory;
 import org.apache.flink.table.calcite.RexAggLocalVariable;
 import org.apache.flink.table.calcite.RexDistinctKeyVariable;
+import org.apache.flink.table.functions.sql.FlinkSqlOperatorTable;
 import org.apache.flink.table.type.DecimalType;
 import org.apache.flink.table.type.InternalType;
 import org.apache.flink.table.type.InternalTypes;
@@ -31,7 +32,6 @@ import org.apache.calcite.rex.RexBuilder;
 import org.apache.calcite.rex.RexInputRef;
 import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.sql.SqlIntervalQualifier;
-import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.sql.parser.SqlParserPos;
 import org.apache.calcite.sql.type.SqlTypeName;
 import org.apache.calcite.tools.RelBuilder;
@@ -79,40 +79,40 @@ public class RexNodeConverter implements ExpressionVisitor<RexNode> {
 
 	private RexNode visitScalarFunc(FunctionDefinition def, List<RexNode> child) {
 		if (BuiltInFunctionDefinitions.IF.equals(def)) {
-			return relBuilder.call(SqlStdOperatorTable.CASE, child);
+			return relBuilder.call(FlinkSqlOperatorTable.CASE, child);
 		} else if (BuiltInFunctionDefinitions.IS_NULL.equals(def)) {
 			return relBuilder.isNull(child.get(0));
 		} else if (BuiltInFunctionDefinitions.PLUS.equals(def)) {
 			if (isString(toInternalType(child.get(0).getType()))) {
 				return relBuilder.call(
-						SqlStdOperatorTable.CONCAT,
+						FlinkSqlOperatorTable.CONCAT,
 						child.get(0),
 						relBuilder.cast(child.get(1), VARCHAR));
 			} else if (isString(toInternalType(child.get(1).getType()))) {
 				return relBuilder.call(
-						SqlStdOperatorTable.CONCAT,
+						FlinkSqlOperatorTable.CONCAT,
 						relBuilder.cast(child.get(0), VARCHAR),
 						child.get(1));
 			} else if (isTimeInterval(toInternalType(child.get(0).getType())) &&
 					child.get(0).getType() == child.get(1).getType()) {
-				return relBuilder.call(SqlStdOperatorTable.PLUS, child);
+				return relBuilder.call(FlinkSqlOperatorTable.PLUS, child);
 			} else if (isTimeInterval(toInternalType(child.get(0).getType()))
 					&& isTemporal(toInternalType(child.get(1).getType()))) {
 				// Calcite has a bug that can't apply INTERVAL + DATETIME (INTERVAL at left)
 				// we manually switch them here
-				return relBuilder.call(SqlStdOperatorTable.DATETIME_PLUS, child);
+				return relBuilder.call(FlinkSqlOperatorTable.DATETIME_PLUS, child);
 			} else if (isTemporal(toInternalType(child.get(0).getType())) &&
 					isTemporal(toInternalType(child.get(1).getType()))) {
-				return relBuilder.call(SqlStdOperatorTable.DATETIME_PLUS, child);
+				return relBuilder.call(FlinkSqlOperatorTable.DATETIME_PLUS, child);
 			} else {
-				return relBuilder.call(SqlStdOperatorTable.PLUS, child);
+				return relBuilder.call(FlinkSqlOperatorTable.PLUS, child);
 			}
 		} else if (BuiltInFunctionDefinitions.MINUS.equals(def)) {
-			return relBuilder.call(SqlStdOperatorTable.MINUS, child);
+			return relBuilder.call(FlinkSqlOperatorTable.MINUS, child);
 		} else if (BuiltInFunctionDefinitions.EQUALS.equals(def)) {
-			return relBuilder.call(SqlStdOperatorTable.EQUALS, child);
+			return relBuilder.call(FlinkSqlOperatorTable.EQUALS, child);
 		} else if (BuiltInFunctionDefinitions.DIVIDE.equals(def)) {
-			return relBuilder.call(SqlStdOperatorTable.DIVIDE, child);
+			return relBuilder.call(FlinkSqlOperatorTable.DIVIDE, child);
 		} else {
 			throw new UnsupportedOperationException(def.getName());
 		}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/CodeGenUtils.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/CodeGenUtils.scala
index 6a31041..41917bc 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/CodeGenUtils.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/CodeGenUtils.scala
@@ -26,6 +26,7 @@ import org.apache.flink.table.`type`._
 import org.apache.flink.table.dataformat.DataFormatConverters.IdentityConverter
 import org.apache.flink.table.dataformat.{Decimal, _}
 import org.apache.flink.table.dataformat.util.BinaryRowUtil.BYTE_ARRAY_BASE_OFFSET
+import org.apache.flink.table.functions.UserDefinedFunction
 import org.apache.flink.table.typeutils.TypeCheckUtils
 import org.apache.flink.table.util.MurmurHashUtil
 import org.apache.flink.types.Row
@@ -68,6 +69,8 @@ object CodeGenUtils {
 
   val BASE_ROW: String = className[BaseRow]
 
+  val JOINED_ROW: String = className[JoinedRow]
+
   val GENERIC_ROW: String = className[GenericRow]
 
   val DECIMAL: String = className[Decimal]
@@ -644,4 +647,9 @@ object CodeGenUtils {
       genToExternal(ctx, t, term)
     }
   }
+
+  def udfFieldName(udf: UserDefinedFunction): String = s"function_${udf.functionIdentifier}"
+
+  def genLogInfo(logTerm: String, format: String, argTerm: String): String =
+    s"""$logTerm.info("$format", $argTerm);"""
 }
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/CodeGeneratorContext.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/CodeGeneratorContext.scala
index 814021c..590b74b 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/CodeGeneratorContext.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/CodeGeneratorContext.scala
@@ -560,7 +560,13 @@ class CodeGeneratorContext(val tableConfig: TableConfig) {
       obj: AnyRef,
       fieldNamePrefix: String,
       fieldTypeTerm: String = null): String = {
-    val fieldTerm = newName(fieldNamePrefix)
+    addReusableObjectWithName(obj, newName(fieldNamePrefix), fieldTypeTerm)
+  }
+
+  def addReusableObjectWithName(
+      obj: AnyRef,
+      fieldTerm: String,
+      fieldTypeTerm: String = null): String = {
     val clsName = Option(fieldTypeTerm).getOrElse(obj.getClass.getCanonicalName)
     addReusableObjectInternal(obj, fieldTerm, clsName)
     fieldTerm
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/AggsHandlerCodeGenerator.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/AggsHandlerCodeGenerator.scala
index 3f0bed6..e07a342 100644
--- a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/AggsHandlerCodeGenerator.scala
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/AggsHandlerCodeGenerator.scala
@@ -46,7 +46,8 @@ class AggsHandlerCodeGenerator(
     relBuilder: RelBuilder,
     inputFieldTypes: Seq[InternalType],
     needRetract: Boolean,
-    copyInputField: Boolean) {
+    copyInputField: Boolean,
+    needAccumulate: Boolean = true) {
 
   private val inputType = new RowType(inputFieldTypes: _*)
 
@@ -142,7 +143,7 @@ class AggsHandlerCodeGenerator(
   def withMerging(
       mergedAccOffset: Int,
       mergedAccOnHeap: Boolean,
-      mergedAccExternalTypes: Array[TypeInformation[_]]): AggsHandlerCodeGenerator = {
+      mergedAccExternalTypes: Array[TypeInformation[_]] = null): AggsHandlerCodeGenerator = {
     this.mergedAccOffset = mergedAccOffset
     this.mergedAccOnHeap = mergedAccOnHeap
     this.mergedAccExternalTypes = mergedAccExternalTypes
@@ -545,21 +546,26 @@ class AggsHandlerCodeGenerator(
   }
 
   private def genAccumulate(): String = {
-    // validation check
-    checkNeededMethods(needAccumulate = true)
+    if (needAccumulate) {
+      // validation check
+      checkNeededMethods(needAccumulate = true)
 
-    val methodName = "accumulate"
-    ctx.startNewLocalVariableStatement(methodName)
+      val methodName = "accumulate"
+      ctx.startNewLocalVariableStatement(methodName)
 
-    // bind input1 as inputRow
-    val exprGenerator = new ExprCodeGenerator(ctx, INPUT_NOT_NULL)
-        .bindInput(inputType, inputTerm = ACCUMULATE_INPUT_TERM)
-    val body = aggActionCodeGens.map(_.accumulate(exprGenerator)).mkString("\n")
-    s"""
-       |${ctx.reuseLocalVariableCode(methodName)}
-       |${ctx.reuseInputUnboxingCode(ACCUMULATE_INPUT_TERM)}
-       |$body
-    """.stripMargin
+      // bind input1 as inputRow
+      val exprGenerator = new ExprCodeGenerator(ctx, INPUT_NOT_NULL)
+          .bindInput(inputType, inputTerm = ACCUMULATE_INPUT_TERM)
+      val body = aggActionCodeGens.map(_.accumulate(exprGenerator)).mkString("\n")
+      s"""
+         |${ctx.reuseLocalVariableCode(methodName)}
+         |${ctx.reuseInputUnboxingCode(ACCUMULATE_INPUT_TERM)}
+         |$body
+         |""".stripMargin
+    } else {
+      genThrowException(
+        "This function not require accumulate method, but the accumulate method is called.")
+    }
   }
 
   private def genRetract(): String = {
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/AggCodeGenHelper.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/AggCodeGenHelper.scala
new file mode 100644
index 0000000..7a4e803
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/AggCodeGenHelper.scala
@@ -0,0 +1,723 @@
+/*
+ * 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.codegen.agg.batch
+
+import org.apache.flink.api.common.ExecutionConfig
+import org.apache.flink.runtime.util.SingleElementIterator
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator
+import org.apache.flink.table.`type`.TypeConverters.{createInternalTypeFromTypeInfo, createInternalTypeInfoFromInternalType}
+import org.apache.flink.table.`type`.{ArrayType, InternalType, MapType, RowType, StringType}
+import org.apache.flink.table.api.TableConfig
+import org.apache.flink.table.codegen.CodeGenUtils.{boxedTypeTermForExternalType, genToExternal, genToInternal, newName, primitiveTypeTermForType}
+import org.apache.flink.table.codegen.OperatorCodeGenerator.STREAM_RECORD
+import org.apache.flink.table.codegen.{CodeGenUtils, CodeGeneratorContext, ExprCodeGenerator, GenerateUtils, GeneratedExpression, OperatorCodeGenerator}
+import org.apache.flink.table.dataformat.{BaseRow, GenericRow}
+import org.apache.flink.table.expressions.{CallExpression, Expression, ExpressionVisitor, FieldReferenceExpression, ResolvedAggInputReference, ResolvedAggLocalReference, RexNodeConverter, SymbolExpression, TypeLiteralExpression, UnresolvedFieldReferenceExpression, ValueLiteralExpression}
+import org.apache.flink.table.functions.utils.UserDefinedFunctionUtils.{getAccumulatorTypeOfAggregateFunction, getAggUserDefinedInputTypes, getResultTypeOfAggregateFunction}
+import org.apache.flink.table.functions.{AggregateFunction, DeclarativeAggregateFunction, UserDefinedFunction}
+import org.apache.flink.table.generated.{GeneratedAggsHandleFunction, GeneratedOperator}
+import org.apache.flink.table.runtime.context.ExecutionContextImpl
+
+import org.apache.calcite.rel.core.AggregateCall
+import org.apache.calcite.rex.RexNode
+import org.apache.calcite.tools.RelBuilder
+
+import scala.collection.JavaConverters._
+
+/**
+  * Batch aggregate code generate helper.
+  */
+object AggCodeGenHelper {
+
+  def getAggBufferNames(
+      auxGrouping: Array[Int], aggregates: Seq[UserDefinedFunction]): Array[Array[String]] = {
+    auxGrouping.zipWithIndex.map {
+      case (_, index) => Array(s"aux_group$index")
+    } ++ aggregates.zipWithIndex.toArray.map {
+      case (a: DeclarativeAggregateFunction, index) =>
+        val idx = auxGrouping.length + index
+        a.aggBufferAttributes.map(attr => s"agg${idx}_${attr.getName}")
+      case (_: AggregateFunction[_, _], index) =>
+        val idx = auxGrouping.length + index
+        Array(s"agg$idx")
+    }
+  }
+
+  def getAggBufferTypes(
+      inputType: RowType, auxGrouping: Array[Int], aggregates: Seq[UserDefinedFunction])
+    : Array[Array[InternalType]] = {
+    auxGrouping.map { index =>
+      Array(inputType.getFieldTypes()(index))
+    } ++ aggregates.map {
+      case a: DeclarativeAggregateFunction => a.getAggBufferTypes
+      case a: AggregateFunction[_, _] =>
+        Array(createInternalTypeFromTypeInfo(getAccumulatorTypeOfAggregateFunction(a)))
+    }.toArray[Array[InternalType]]
+  }
+
+  def getUdaggs(
+      aggregates: Seq[UserDefinedFunction]): Map[AggregateFunction[_, _], String] = {
+    aggregates
+        .filter(a => a.isInstanceOf[AggregateFunction[_, _]])
+        .map(a => a -> CodeGenUtils.udfFieldName(a)).toMap
+        .asInstanceOf[Map[AggregateFunction[_, _], String]]
+  }
+
+  def projectRowType(rowType: RowType, mapping: Array[Int]): RowType = {
+    new RowType(mapping.map(rowType.getTypeAt), mapping.map(rowType.getFieldNames()(_)))
+  }
+
+  /**
+    * Add agg handler to class member and open it.
+    */
+  private[flink] def addAggsHandler(
+      aggsHandler: GeneratedAggsHandleFunction,
+      ctx: CodeGeneratorContext,
+      aggsHandlerCtx: CodeGeneratorContext): String = {
+    ctx.addReusableInnerClass(aggsHandler.getClassName, aggsHandler.getCode)
+    val handler = CodeGenUtils.newName("handler")
+    ctx.addReusableMember(s"${aggsHandler.getClassName} $handler = null;")
+    val aggRefers = ctx.addReusableObject(aggsHandlerCtx.references.toArray, "Object[]")
+    ctx.addReusableOpenStatement(
+      s"""
+         |$handler = new ${aggsHandler.getClassName}($aggRefers);
+         |$handler.open(new ${classOf[ExecutionContextImpl].getCanonicalName}(
+         |  this, getRuntimeContext()));
+       """.stripMargin)
+    ctx.addReusableCloseStatement(s"$handler.close();")
+    handler
+  }
+
+  /**
+    * The generated codes only supports the comparison of the key terms
+    * in the form of binary row with only one memory segment.
+    */
+  private[flink] def genGroupKeyChangedCheckCode(
+      currentKeyTerm: String,
+      lastKeyTerm: String): String = {
+    s"""
+       |$currentKeyTerm.getSizeInBytes() != $lastKeyTerm.getSizeInBytes() ||
+       |  !(org.apache.flink.table.dataformat.util.BinaryRowUtil.byteArrayEquals(
+       |     $currentKeyTerm.getSegments()[0].getHeapMemory(),
+       |     $lastKeyTerm.getSegments()[0].getHeapMemory(),
+       |     $currentKeyTerm.getSizeInBytes()))
+       """.stripMargin.trim
+  }
+
+  def genSortAggCodes(
+      isMerge: Boolean,
+      isFinal: Boolean,
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      grouping: Array[Int],
+      auxGrouping: Array[Int],
+      aggCallToAggFunction: Seq[(AggregateCall, UserDefinedFunction)],
+      aggArgs: Array[Array[Int]],
+      aggregates: Seq[UserDefinedFunction],
+      udaggs: Map[AggregateFunction[_, _], String],
+      inputTerm: String,
+      inputType: RowType,
+      aggBufferNames: Array[Array[String]],
+      aggBufferTypes: Array[Array[InternalType]],
+      outputType: RowType,
+      forHashAgg: Boolean = false): (String, String, GeneratedExpression) = {
+    // gen code to apply aggregate functions to grouping elements
+    val argsMapping = buildAggregateArgsMapping(
+      isMerge, grouping.length, inputType, auxGrouping, aggArgs, aggBufferTypes)
+
+    val aggBufferExprs = genFlatAggBufferExprs(
+      isMerge,
+      ctx,
+      config,
+      builder,
+      auxGrouping,
+      aggregates,
+      argsMapping,
+      aggBufferNames,
+      aggBufferTypes)
+
+    val initAggBufferCode = genInitFlatAggregateBuffer(
+      ctx,
+      config,
+      builder,
+      inputType,
+      inputTerm,
+      grouping,
+      auxGrouping,
+      aggregates,
+      udaggs,
+      aggBufferExprs,
+      forHashAgg)
+
+    val doAggregateCode = genAggregateByFlatAggregateBuffer(
+      isMerge,
+      ctx,
+      config,
+      builder,
+      inputType,
+      inputTerm,
+      auxGrouping,
+      aggCallToAggFunction,
+      aggregates,
+      udaggs,
+      argsMapping,
+      aggBufferNames,
+      aggBufferTypes,
+      aggBufferExprs)
+
+    val aggOutputExpr = genSortAggOutputExpr(
+      isMerge,
+      isFinal,
+      ctx,
+      config,
+      builder,
+      grouping,
+      auxGrouping,
+      aggregates,
+      udaggs,
+      argsMapping,
+      aggBufferNames,
+      aggBufferTypes,
+      aggBufferExprs,
+      outputType)
+
+    (initAggBufferCode, doAggregateCode, aggOutputExpr)
+  }
+
+  /**
+    * Build an arg mapping for reference binding. The mapping will be a 2-dimension array.
+    * The first dimension represents the aggregate index, the order is same with agg calls in plan.
+    * The second dimension information represents input count of the aggregate. The meaning will
+    * be different depends on whether we should do merge.
+    *
+    * In non-merge case, aggregate functions will treat inputs as operands. In merge case, the
+    * input is local aggregation's buffer, we need to merge with our local aggregate buffers.
+    */
+  private[flink] def buildAggregateArgsMapping(
+      isMerge: Boolean,
+      aggBufferOffset: Int,
+      inputType: RowType,
+      auxGrouping: Array[Int],
+      aggArgs: Array[Array[Int]],
+      aggBufferTypes: Array[Array[InternalType]]): Array[Array[(Int, InternalType)]] = {
+    val auxGroupingMapping = auxGrouping.indices.map {
+      i => Array[(Int, InternalType)]((i, aggBufferTypes(i)(0)))
+    }.toArray
+
+    val aggCallMapping = if (isMerge) {
+      var offset = aggBufferOffset + auxGrouping.length
+      aggBufferTypes.slice(auxGrouping.length, aggBufferTypes.length).map { types =>
+        val baseOffset = offset
+        offset = offset + types.length
+        types.indices.map(index => (baseOffset + index, types(index))).toArray
+      }
+    } else {
+      aggArgs.map(args => args.map(i => (i, inputType.getTypeAt(i))))
+    }
+
+    auxGroupingMapping ++ aggCallMapping
+  }
+
+  def newLocalReference(
+      ctx: CodeGeneratorContext,
+      resultTerm: String,
+      resultType: InternalType): ResolvedAggLocalReference = {
+    val nullTerm = resultTerm + "IsNull"
+    ctx.addReusableMember(s"${primitiveTypeTermForType(resultType)} $resultTerm;")
+    ctx.addReusableMember(s"boolean $nullTerm;")
+    new ResolvedAggLocalReference(resultTerm, nullTerm, resultType)
+  }
+
+  /**
+    * Resolves the given expression to a resolved Expression.
+    *
+    * @param isMerge this is called from merge() method
+    */
+  private case class ResolveReference(
+      ctx: CodeGeneratorContext,
+      isMerge: Boolean,
+      agg: DeclarativeAggregateFunction,
+      aggIndex: Int,
+      argsMapping: Array[Array[(Int, InternalType)]],
+      aggBufferTypes: Array[Array[InternalType]]) extends ExpressionVisitor[Expression] {
+
+    override def visitCall(call: CallExpression): Expression = {
+      new CallExpression(
+        call.getFunctionDefinition,
+        call.getChildren.asScala.map(_.accept(this)).asJava)
+    }
+
+    override def visitSymbol(symbolExpression: SymbolExpression): Expression = {
+      symbolExpression
+    }
+
+    override def visitValueLiteral(valueLiteralExpression: ValueLiteralExpression): Expression = {
+      valueLiteralExpression
+    }
+
+    override def visitFieldReference(input: FieldReferenceExpression): Expression = {
+      input
+    }
+
+    override def visitTypeLiteral(typeLiteral: TypeLiteralExpression): Expression = {
+      typeLiteral
+    }
+
+    private def visitUnresolvedFieldReference(
+        input: UnresolvedFieldReferenceExpression): Expression = {
+      agg.aggBufferAttributes.indexOf(input) match {
+        case -1 =>
+          // We always use UnresolvedFieldReference to represent reference of input field.
+          // In non-merge case, the input is operand of the aggregate function. But in merge
+          // case, the input is aggregate buffers which sent by local aggregate.
+          val localIndex = if (isMerge) {
+            agg.mergeOperands.indexOf(input)
+          } else {
+            agg.operands.indexOf(input)
+          }
+          val (inputIndex, inputType) = argsMapping(aggIndex)(localIndex)
+          new ResolvedAggInputReference(input.getName, inputIndex, inputType)
+        case localIndex =>
+          val variableName = s"agg${aggIndex}_${input.getName}"
+          newLocalReference(
+            ctx, variableName, aggBufferTypes(aggIndex)(localIndex))
+      }
+    }
+
+    override def visit(other: Expression): Expression = {
+      other match {
+        case u : UnresolvedFieldReferenceExpression => visitUnresolvedFieldReference(u)
+        case _ => other
+      }
+    }
+  }
+
+  /**
+    * Declare all aggregate buffer variables, store these variables in class members
+    */
+  private[flink] def genFlatAggBufferExprs(
+      isMerge: Boolean,
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      auxGrouping: Array[Int],
+      aggregates: Seq[UserDefinedFunction],
+      argsMapping: Array[Array[(Int, InternalType)]],
+      aggBufferNames: Array[Array[String]],
+      aggBufferTypes: Array[Array[InternalType]]): Seq[GeneratedExpression] = {
+    val exprCodegen = new ExprCodeGenerator(ctx, false)
+    val converter = new RexNodeConverter(builder)
+
+    val accessAuxGroupingExprs = auxGrouping.indices.map {
+      idx => newLocalReference(ctx, aggBufferNames(idx)(0), aggBufferTypes(idx)(0))
+    }.map(_.accept(converter)).map(exprCodegen.generateExpression)
+
+    val aggCallExprs = aggregates.zipWithIndex.flatMap {
+      case (agg: DeclarativeAggregateFunction, aggIndex: Int) =>
+        val idx = auxGrouping.length + aggIndex
+        agg.aggBufferAttributes.map(_.accept(
+          ResolveReference(ctx, isMerge, agg, idx, argsMapping, aggBufferTypes)))
+      case (_: AggregateFunction[_, _], aggIndex: Int) =>
+        val idx = auxGrouping.length + aggIndex
+        val variableName = aggBufferNames(idx)(0)
+        Some(newLocalReference(ctx, variableName, aggBufferTypes(idx)(0)))
+    }.map(_.accept(converter)).map(exprCodegen.generateExpression)
+
+    accessAuxGroupingExprs ++ aggCallExprs
+  }
+
+  /**
+    * Generate codes which will init the aggregate buffer.
+    */
+  private[flink] def genInitFlatAggregateBuffer(
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      inputType: RowType,
+      inputTerm: String,
+      grouping: Array[Int],
+      auxGrouping: Array[Int],
+      aggregates: Seq[UserDefinedFunction],
+      udaggs: Map[AggregateFunction[_, _], String],
+      aggBufferExprs: Seq[GeneratedExpression],
+      forHashAgg: Boolean = false): String = {
+    val exprCodegen = new ExprCodeGenerator(ctx, false)
+        .bindInput(inputType, inputTerm = inputTerm, inputFieldMapping = Some(auxGrouping))
+
+    val initAuxGroupingExprs = {
+      if (forHashAgg) {
+        // access fallbackInput
+        auxGrouping.indices.map(idx => idx + grouping.length).toArray
+      } else {
+        // access input
+        auxGrouping
+      }
+    }.map { idx =>
+      GenerateUtils.generateFieldAccess(ctx, inputType, inputTerm, idx)
+    }
+
+    val initAggCallBufferExprs = aggregates.flatMap {
+      case (agg: DeclarativeAggregateFunction) =>
+        agg.initialValuesExpressions
+      case (agg: AggregateFunction[_, _]) =>
+        Some(agg)
+    }.map {
+      case (expr: Expression) => expr.accept(new RexNodeConverter(builder))
+      case t@_ => t
+    }.map {
+      case (rex: RexNode) => exprCodegen.generateExpression(rex)
+      case (agg: AggregateFunction[_, _]) =>
+        val resultTerm = s"${udaggs(agg)}.createAccumulator()"
+        val nullTerm = "false"
+        val resultType = getAccumulatorTypeOfAggregateFunction(agg)
+        GeneratedExpression(
+          genToInternal(ctx, resultType, resultTerm),
+          nullTerm,
+          "",
+          createInternalTypeFromTypeInfo(resultType))
+    }
+
+    val initAggBufferExprs = initAuxGroupingExprs ++ initAggCallBufferExprs
+    require(aggBufferExprs.length == initAggBufferExprs.length)
+
+    aggBufferExprs.zip(initAggBufferExprs).map {
+      case (aggBufVar, initExpr) =>
+        val resultCode = aggBufVar.resultType match {
+          case _: StringType | _: RowType | _: ArrayType | _: MapType =>
+            val serializer = createInternalTypeInfoFromInternalType(aggBufVar.resultType)
+                .createSerializer(new ExecutionConfig)
+            val term = ctx.addReusableObject(
+              serializer, "serializer", serializer.getClass.getCanonicalName)
+            s"$term.copy(${initExpr.resultTerm})"
+          case _ => initExpr.resultTerm
+        }
+        s"""
+           |${initExpr.code}
+           |${aggBufVar.nullTerm} = ${initExpr.nullTerm};
+           |${aggBufVar.resultTerm} = $resultCode;
+         """.stripMargin.trim
+    } mkString "\n"
+  }
+
+  private[flink] def genAggregateByFlatAggregateBuffer(
+      isMerge: Boolean,
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      inputType: RowType,
+      inputTerm: String,
+      auxGrouping: Array[Int],
+      aggCallToAggFunction: Seq[(AggregateCall, UserDefinedFunction)],
+      aggregates: Seq[UserDefinedFunction],
+      udaggs: Map[AggregateFunction[_, _], String],
+      argsMapping: Array[Array[(Int, InternalType)]],
+      aggBufferNames: Array[Array[String]],
+      aggBufferTypes: Array[Array[InternalType]],
+      aggBufferExprs: Seq[GeneratedExpression]): String = {
+    if (isMerge) {
+      genMergeFlatAggregateBuffer(
+        ctx,
+        config,
+        builder,
+        inputTerm,
+        inputType,
+        auxGrouping,
+        aggregates,
+        udaggs,
+        argsMapping,
+        aggBufferNames,
+        aggBufferTypes,
+        aggBufferExprs)
+    } else {
+      genAccumulateFlatAggregateBuffer(
+        ctx,
+        config,
+        builder,
+        inputTerm,
+        inputType,
+        auxGrouping,
+        aggCallToAggFunction,
+        udaggs,
+        argsMapping,
+        aggBufferNames,
+        aggBufferTypes,
+        aggBufferExprs)
+    }
+  }
+
+  def genSortAggOutputExpr(
+      isMerge: Boolean,
+      isFinal: Boolean,
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      grouping: Array[Int],
+      auxGrouping: Array[Int],
+      aggregates: Seq[UserDefinedFunction],
+      udaggs: Map[AggregateFunction[_, _], String],
+      argsMapping: Array[Array[(Int, InternalType)]],
+      aggBufferNames: Array[Array[String]],
+      aggBufferTypes: Array[Array[InternalType]],
+      aggBufferExprs: Seq[GeneratedExpression],
+      outputType: RowType): GeneratedExpression = {
+    val valueRow = CodeGenUtils.newName("valueRow")
+    val resultCodegen = new ExprCodeGenerator(ctx, false)
+    if (isFinal) {
+      val getValueExprs = genGetValueFromFlatAggregateBuffer(
+        isMerge,
+        ctx,
+        config,
+        builder,
+        auxGrouping,
+        aggregates,
+        udaggs,
+        argsMapping,
+        aggBufferNames,
+        aggBufferTypes,
+        outputType)
+      val valueRowType = new RowType(getValueExprs.map(_.resultType): _*)
+      resultCodegen.generateResultExpression(
+        getValueExprs, valueRowType, classOf[GenericRow], valueRow)
+    } else {
+      val valueRowType = new RowType(aggBufferExprs.map(_.resultType): _*)
+      resultCodegen.generateResultExpression(
+        aggBufferExprs, valueRowType, classOf[GenericRow], valueRow)
+    }
+  }
+
+  /**
+    * Generate expressions which will get final aggregate value from aggregate buffers.
+    */
+  private[flink] def genGetValueFromFlatAggregateBuffer(
+      isMerge: Boolean,
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      auxGrouping: Array[Int],
+      aggregates: Seq[UserDefinedFunction],
+      udaggs: Map[AggregateFunction[_, _], String],
+      argsMapping: Array[Array[(Int, InternalType)]],
+      aggBufferNames: Array[Array[String]],
+      aggBufferTypes: Array[Array[InternalType]],
+      outputType: RowType): Seq[GeneratedExpression] = {
+    val exprCodegen = new ExprCodeGenerator(ctx, false)
+
+    val auxGroupingExprs = auxGrouping.indices.map { idx =>
+      val resultTerm = aggBufferNames(idx)(0)
+      val nullTerm = s"${resultTerm}IsNull"
+      GeneratedExpression(resultTerm, nullTerm, "", aggBufferTypes(idx)(0))
+    }
+
+    val aggExprs = aggregates.zipWithIndex.map {
+      case (agg: DeclarativeAggregateFunction, aggIndex) =>
+        val idx = auxGrouping.length + aggIndex
+        agg.getValueExpression.accept(ResolveReference(
+          ctx, isMerge, agg, idx, argsMapping, aggBufferTypes))
+      case (agg: AggregateFunction[_, _], aggIndex) =>
+        val idx = auxGrouping.length + aggIndex
+        (agg, idx)
+    }.map {
+      case (expr: Expression) => expr.accept(new RexNodeConverter(builder))
+      case t@_ => t
+    }.map {
+      case (rex: RexNode) => exprCodegen.generateExpression(rex)
+      case (agg: AggregateFunction[_, _], aggIndex: Int) =>
+        val resultType = getResultTypeOfAggregateFunction(agg)
+        val accType = getAccumulatorTypeOfAggregateFunction(agg)
+        val resultTerm = genToInternal(ctx, resultType,
+          s"${udaggs(agg)}.getValue(${genToExternal(ctx, accType, aggBufferNames(aggIndex)(0))})")
+        val nullTerm = s"${aggBufferNames(aggIndex)(0)}IsNull"
+        GeneratedExpression(resultTerm, nullTerm, "", createInternalTypeFromTypeInfo(resultType))
+    }
+
+    auxGroupingExprs ++ aggExprs
+  }
+
+  /**
+    * Generate codes which will read input and merge the aggregate buffers.
+    */
+  private[flink] def genMergeFlatAggregateBuffer(
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      inputTerm: String,
+      inputType: RowType,
+      auxGrouping: Array[Int],
+      aggregates: Seq[UserDefinedFunction],
+      udaggs: Map[AggregateFunction[_, _], String],
+      argsMapping: Array[Array[(Int, InternalType)]],
+      aggBufferNames: Array[Array[String]],
+      aggBufferTypes: Array[Array[InternalType]],
+      aggBufferExprs: Seq[GeneratedExpression]): String = {
+    val exprCodegen = new ExprCodeGenerator(ctx, false).bindInput(inputType, inputTerm = inputTerm)
+
+    // flat map to get flat agg buffers.
+    aggregates.zipWithIndex.flatMap {
+      case (agg: DeclarativeAggregateFunction, aggIndex) =>
+        val idx = auxGrouping.length + aggIndex
+        agg.mergeExpressions.map(
+          _.accept(ResolveReference(ctx, isMerge = true, agg, idx, argsMapping, aggBufferTypes)))
+      case (agg: AggregateFunction[_, _], aggIndex) =>
+        val idx = auxGrouping.length + aggIndex
+        Some(agg, idx)
+    }.zip(aggBufferExprs.slice(auxGrouping.length, aggBufferExprs.size)).map {
+      // DeclarativeAggregateFunction
+      case ((expr: Expression), aggBufVar) =>
+        val mergeExpr = exprCodegen.generateExpression(expr.accept(new RexNodeConverter(builder)))
+        s"""
+           |${mergeExpr.code}
+           |${aggBufVar.nullTerm} = ${mergeExpr.nullTerm};
+           |if (!${mergeExpr.nullTerm}) {
+           |  ${mergeExpr.copyResultTermToTargetIfChanged(ctx, aggBufVar.resultTerm)}
+           |}
+           """.stripMargin.trim
+      // UserDefinedAggregateFunction
+      case ((agg: AggregateFunction[_, _], aggIndex: Int), aggBufVar) =>
+        val (inputIndex, inputType) = argsMapping(aggIndex)(0)
+        val inputRef = new ResolvedAggInputReference(inputTerm, inputIndex, inputType)
+        val inputExpr = exprCodegen.generateExpression(
+          inputRef.accept(new RexNodeConverter(builder)))
+        val singleIterableClass = classOf[SingleElementIterator[_]].getCanonicalName
+
+        val externalAccT = getAccumulatorTypeOfAggregateFunction(agg)
+        val javaField = boxedTypeTermForExternalType(externalAccT)
+        val tmpAcc = newName("tmpAcc")
+        s"""
+           |final $singleIterableClass accIt$aggIndex = new  $singleIterableClass();
+           |accIt$aggIndex.set(${genToExternal(ctx, externalAccT, inputExpr.resultTerm)});
+           |$javaField $tmpAcc = ${genToExternal(ctx, externalAccT, aggBufferNames(aggIndex)(0))};
+           |${udaggs(agg)}.merge($tmpAcc, accIt$aggIndex);
+           |${aggBufferNames(aggIndex)(0)} = ${genToInternal(ctx, externalAccT, tmpAcc)};
+           |${aggBufVar.nullTerm} = ${aggBufferNames(aggIndex)(0)}IsNull || ${inputExpr.nullTerm};
+         """.stripMargin
+    } mkString "\n"
+  }
+
+  /**
+    * Generate codes which will read input and accumulating aggregate buffers.
+    */
+  private[flink] def genAccumulateFlatAggregateBuffer(
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      inputTerm: String,
+      inputType: RowType,
+      auxGrouping: Array[Int],
+      aggCallToAggFunction: Seq[(AggregateCall, UserDefinedFunction)],
+      udaggs: Map[AggregateFunction[_, _], String],
+      argsMapping: Array[Array[(Int, InternalType)]],
+      aggBufferNames: Array[Array[String]],
+      aggBufferTypes: Array[Array[InternalType]],
+      aggBufferExprs: Seq[GeneratedExpression]): String = {
+    val exprCodegen = new ExprCodeGenerator(ctx, false).bindInput(inputType, inputTerm = inputTerm)
+
+    // flat map to get flat agg buffers.
+    aggCallToAggFunction.zipWithIndex.flatMap {
+      case (aggCallToAggFun, aggIndex) =>
+        val idx = auxGrouping.length + aggIndex
+        val aggCall = aggCallToAggFun._1
+        aggCallToAggFun._2 match {
+          case agg: DeclarativeAggregateFunction =>
+            agg.accumulateExpressions.map(_.accept(
+              ResolveReference(ctx, isMerge = false, agg, idx, argsMapping, aggBufferTypes)))
+                .map(e => (e, aggCall))
+          case agg: AggregateFunction[_, _] =>
+            val idx = auxGrouping.length + aggIndex
+            Some(agg, idx, aggCall)
+        }
+    }.zip(aggBufferExprs.slice(auxGrouping.length, aggBufferExprs.size)).map {
+      // DeclarativeAggregateFunction
+      case ((expr: Expression, aggCall: AggregateCall), aggBufVar) =>
+        val accExpr = exprCodegen.generateExpression(expr.accept(new RexNodeConverter(builder)))
+        (s"""
+            |${accExpr.code}
+            |${aggBufVar.nullTerm} = ${accExpr.nullTerm};
+            |if (!${accExpr.nullTerm}) {
+            |  ${accExpr.copyResultTermToTargetIfChanged(ctx, aggBufVar.resultTerm)}
+            |}
+           """.stripMargin, aggCall.filterArg)
+      // UserDefinedAggregateFunction
+      case ((agg: AggregateFunction[_, _], aggIndex: Int, aggCall: AggregateCall),
+      aggBufVar) =>
+        val inFields = argsMapping(aggIndex)
+        val externalAccType = getAccumulatorTypeOfAggregateFunction(agg)
+
+        val inputExprs = inFields.map {
+          f =>
+            val inputRef = new ResolvedAggInputReference(inputTerm, f._1, f._2)
+            exprCodegen.generateExpression(inputRef.accept(new RexNodeConverter(builder)))
+        }
+
+        val externalUDITypes = getAggUserDefinedInputTypes(
+          agg, externalAccType, inputExprs.map(_.resultType))
+        val parameters = inputExprs.zipWithIndex.map {
+          case (expr, i) =>
+            s"${expr.nullTerm} ? null : " +
+                s"${ genToExternal(ctx, externalUDITypes(i), expr.resultTerm)}"
+        }
+
+        val javaTerm = boxedTypeTermForExternalType(externalAccType)
+        val tmpAcc = newName("tmpAcc")
+        val innerCode =
+          s"""
+             |  $javaTerm $tmpAcc = ${
+            genToExternal(ctx, externalAccType, aggBufferNames(aggIndex)(0))};
+             |  ${udaggs(agg)}.accumulate($tmpAcc, ${parameters.mkString(", ")});
+             |  ${aggBufferNames(aggIndex)(0)} = ${genToInternal(ctx, externalAccType, tmpAcc)};
+             |  ${aggBufVar.nullTerm} = false;
+           """.stripMargin
+        (innerCode, aggCall.filterArg)
+    }.map({
+      case (innerCode, filterArg) =>
+        if (filterArg >= 0) {
+          s"""
+             |if ($inputTerm.getBoolean($filterArg)) {
+             | $innerCode
+             |}
+          """.stripMargin
+        } else {
+          innerCode
+        }
+    }) mkString "\n"
+  }
+
+  /**
+    * Generate a operator with adding a hasInput field to agg operator.
+    */
+  private[flink] def generateOperator(
+      ctx: CodeGeneratorContext,
+      name: String,
+      operatorBaseClass: String,
+      processCode: String,
+      endInputCode: String,
+      inputType: RowType,
+      config: TableConfig): GeneratedOperator[OneInputStreamOperator[BaseRow, BaseRow]] = {
+    ctx.addReusableMember("private boolean hasInput = false;")
+    ctx.addReusableMember(s"$STREAM_RECORD element = new $STREAM_RECORD((Object)null);")
+    OperatorCodeGenerator.generateOneInputStreamOperator(
+      ctx,
+      name,
+      processCode,
+      endInputCode,
+      inputType,
+      config,
+      lazyInputUnboxingCode = true)
+  }
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/AggWithoutKeysCodeGenerator.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/AggWithoutKeysCodeGenerator.scala
new file mode 100644
index 0000000..25a4cee
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/AggWithoutKeysCodeGenerator.scala
@@ -0,0 +1,120 @@
+/*
+ * 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.codegen.agg.batch
+
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator
+import org.apache.flink.table.`type`.RowType
+import org.apache.flink.table.codegen.{CodeGenUtils, CodeGeneratorContext}
+import org.apache.flink.table.codegen.OperatorCodeGenerator.generateCollect
+import org.apache.flink.table.codegen.agg.batch.AggCodeGenHelper.genSortAggCodes
+import org.apache.flink.table.dataformat.BaseRow
+import org.apache.flink.table.functions.AggregateFunction
+import org.apache.flink.table.generated.GeneratedOperator
+import org.apache.flink.table.plan.util.AggregateInfoList
+import org.apache.flink.table.runtime.TableStreamOperator
+
+import org.apache.calcite.tools.RelBuilder
+
+/**
+  * Generate a agg operator without keys, auxGrouping must be empty too.
+  */
+object AggWithoutKeysCodeGenerator {
+
+  def genWithoutKeys(
+      ctx: CodeGeneratorContext,
+      builder: RelBuilder,
+      aggInfoList: AggregateInfoList,
+      inputType: RowType,
+      outputType: RowType,
+      isMerge: Boolean,
+      isFinal: Boolean,
+      prefix: String): GeneratedOperator[OneInputStreamOperator[BaseRow, BaseRow]] = {
+    val aggCallToAggFunction = aggInfoList.aggInfos.map(info => (info.agg, info.function))
+    val aggregates = aggCallToAggFunction.map(_._2)
+    val udaggs = AggCodeGenHelper.getUdaggs(aggregates)
+    val aggBufferNames = AggCodeGenHelper.getAggBufferNames(Array(), aggregates)
+    val aggBufferTypes = AggCodeGenHelper.getAggBufferTypes(inputType, Array(), aggregates)
+    val aggArgs = aggInfoList.aggInfos.map(_.argIndexes)
+
+    val config = ctx.tableConfig
+    val inputTerm = CodeGenUtils.DEFAULT_INPUT1_TERM
+
+    // register udagg
+    aggregates.filter(a => a.isInstanceOf[AggregateFunction[_, _]])
+        .map(a => ctx.addReusableFunction(a))
+
+    val (initAggBufferCode, doAggregateCode, aggOutputExpr) = genSortAggCodes(
+      isMerge,
+      isFinal,
+      ctx,
+      config,
+      builder,
+      Array(),
+      Array(),
+      aggCallToAggFunction,
+      aggArgs,
+      aggregates,
+      udaggs,
+      inputTerm,
+      inputType,
+      aggBufferNames,
+      aggBufferTypes,
+      outputType)
+
+    val processCode =
+      s"""
+         |if (!hasInput) {
+         |  hasInput = true;
+         |  // init agg buffer
+         |  $initAggBufferCode
+         |}
+         |
+         |${ctx.reuseInputUnboxingCode()}
+         |$doAggregateCode
+         |""".stripMargin.trim
+
+    // if the input is empty in final phase, we should output default values
+    val endInputCode = if (isFinal) {
+      s"""
+         |if (!hasInput) {
+         |  $initAggBufferCode
+         |}
+         |${aggOutputExpr.code}
+         |${generateCollect(aggOutputExpr.resultTerm)}
+         |""".stripMargin
+    } else {
+      s"""
+         |if (hasInput) {
+         |  ${aggOutputExpr.code}
+         |  ${generateCollect(aggOutputExpr.resultTerm)}
+         |}""".stripMargin
+    }
+
+    val className =
+      if (isFinal) s"${prefix}AggregateWithoutKeys" else s"Local${prefix}AggregateWithoutKeys"
+    AggCodeGenHelper.generateOperator(
+      ctx,
+      className,
+      classOf[TableStreamOperator[BaseRow]].getCanonicalName,
+      processCode,
+      endInputCode,
+      inputType,
+      config)
+  }
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/HashAggCodeGenHelper.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/HashAggCodeGenHelper.scala
new file mode 100644
index 0000000..98b2947
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/HashAggCodeGenHelper.scala
@@ -0,0 +1,860 @@
+/*
+ * 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.codegen.agg.batch
+
+import org.apache.flink.api.java.tuple.{Tuple2 => JTuple2}
+import org.apache.flink.metrics.Gauge
+import org.apache.flink.table.`type`.{InternalType, RowType}
+import org.apache.flink.table.api.TableConfig
+import org.apache.flink.table.calcite.FlinkPlannerImpl
+import org.apache.flink.table.codegen.CodeGenUtils.{binaryRowFieldSetAccess, binaryRowSetNull}
+import org.apache.flink.table.codegen.agg.batch.AggCodeGenHelper.buildAggregateArgsMapping
+import org.apache.flink.table.codegen.{CodeGenUtils, CodeGeneratorContext, ExprCodeGenerator, GenerateUtils, GeneratedExpression, OperatorCodeGenerator, SortCodeGenerator}
+import org.apache.flink.table.dataformat.{BaseRow, BinaryRow, GenericRow, JoinedRow}
+import org.apache.flink.table.expressions.{CallExpression, Expression, ExpressionVisitor, FieldReferenceExpression, ResolvedAggInputReference, RexNodeConverter, SymbolExpression, TypeLiteralExpression, UnresolvedFieldReferenceExpression, ValueLiteralExpression}
+import org.apache.flink.table.functions.{AggregateFunction, DeclarativeAggregateFunction, UserDefinedFunction}
+import org.apache.flink.table.generated.{NormalizedKeyComputer, RecordComparator}
+import org.apache.flink.table.runtime.aggregate.{BytesHashMap, BytesHashMapSpillMemorySegmentPool}
+import org.apache.flink.table.runtime.sort.BufferedKVExternalSorter
+import org.apache.flink.table.typeutils.BinaryRowSerializer
+
+import org.apache.calcite.rel.core.AggregateCall
+import org.apache.calcite.tools.RelBuilder
+
+import scala.collection.JavaConversions._
+
+object HashAggCodeGenHelper {
+
+  def prepareHashAggKVTypes(
+      ctx: CodeGeneratorContext,
+      aggMapKeyTypesTerm: String,
+      aggBufferTypesTerm: String,
+      aggMapKeyType: RowType,
+      aggBufferType: RowType): Unit = {
+    ctx.addReusableObjectWithName(aggMapKeyType.getFieldTypes, aggMapKeyTypesTerm)
+    ctx.addReusableObjectWithName(aggBufferType.getFieldTypes, aggBufferTypesTerm)
+  }
+
+  private[flink] def prepareHashAggMap(
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      reservedManagedMemory: Long,
+      maxManagedMemory: Long,
+      groupKeyTypesTerm: String,
+      aggBufferTypesTerm: String,
+      aggregateMapTerm: String): Unit = {
+    // create aggregate map
+    val mapTypeTerm = classOf[BytesHashMap].getName
+    ctx.addReusableMember(s"private transient $mapTypeTerm $aggregateMapTerm;")
+    ctx.addReusableOpenStatement(s"$aggregateMapTerm " +
+        s"= new $mapTypeTerm(" +
+        s"this.getContainingTask()," +
+        s"this.getContainingTask().getEnvironment().getMemoryManager()," +
+        s"${reservedManagedMemory}L," +
+        s" $groupKeyTypesTerm," +
+        s" $aggBufferTypesTerm);")
+    // close aggregate map and release memory segments
+    ctx.addReusableCloseStatement(s"$aggregateMapTerm.free();")
+    ctx.addReusableCloseStatement(s"")
+  }
+
+  private[flink] def prepareTermForAggMapIteration(
+      ctx: CodeGeneratorContext,
+      outputTerm: String,
+      outputType: RowType,
+      aggMapKeyType: RowType,
+      aggBufferType: RowType,
+      outputClass: Class[_ <: BaseRow]): (String, String, String) = {
+    // prepare iteration var terms
+    val reuseAggMapKeyTerm = CodeGenUtils.newName("reuseAggMapKey")
+    val reuseAggBufferTerm = CodeGenUtils.newName("reuseAggBuffer")
+    val reuseAggMapEntryTerm = CodeGenUtils.newName("reuseAggMapEntry")
+    // gen code to prepare agg output using agg buffer and key from the aggregate map
+    val binaryRow = classOf[BinaryRow].getName
+    val mapEntryTypeTerm = classOf[BytesHashMap.Entry].getCanonicalName
+
+    ctx.addReusableOutputRecord(outputType, outputClass, outputTerm)
+    ctx.addReusableMember(
+      s"private transient $binaryRow $reuseAggMapKeyTerm = " +
+          s"new $binaryRow(${aggMapKeyType.getArity});")
+    ctx.addReusableMember(
+      s"private transient $binaryRow $reuseAggBufferTerm = " +
+          s"new $binaryRow(${aggBufferType.getArity});")
+    ctx.addReusableMember(
+      s"private transient $mapEntryTypeTerm $reuseAggMapEntryTerm = " +
+          s"new $mapEntryTypeTerm($reuseAggMapKeyTerm, $reuseAggBufferTerm);"
+    )
+    (reuseAggMapEntryTerm, reuseAggMapKeyTerm, reuseAggBufferTerm)
+  }
+
+  private[flink] def genHashAggCodes(
+      isMerge: Boolean,
+      isFinal: Boolean,
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      groupingAndAuxGrouping: (Array[Int], Array[Int]),
+      inputTerm: String,
+      inputType: RowType,
+      aggregateCalls: Seq[AggregateCall],
+      aggCallToAggFunction: Seq[(AggregateCall, UserDefinedFunction)],
+      aggArgs: Array[Array[Int]],
+      aggregates: Seq[UserDefinedFunction],
+      currentAggBufferTerm: String,
+      aggBufferRowType: RowType,
+      aggBufferNames: Array[Array[String]],
+      aggBufferTypes: Array[Array[InternalType]],
+      outputTerm: String,
+      outputType: RowType,
+      groupKeyTerm: String,
+      aggBufferTerm: String): (GeneratedExpression, GeneratedExpression, GeneratedExpression) = {
+    val (grouping, auxGrouping) = groupingAndAuxGrouping
+    // build mapping for DeclarativeAggregationFunction binding references
+    val argsMapping = buildAggregateArgsMapping(
+      isMerge, grouping.length, inputType, auxGrouping, aggArgs, aggBufferTypes)
+    val aggBuffMapping = buildAggregateAggBuffMapping(aggBufferTypes)
+    // gen code to create empty agg buffer
+    val initedAggBuffer = genReusableEmptyAggBuffer(
+      ctx, config, builder, inputTerm, inputType, auxGrouping, aggregates, aggBufferRowType)
+    if (auxGrouping.isEmpty) {
+      // create an empty agg buffer and initialized make it reusable
+      ctx.addReusableOpenStatement(initedAggBuffer.code)
+    }
+    // gen code to update agg buffer from the aggregate map
+    val aggregate = genAggregate(
+      isMerge,
+      ctx,
+      config,
+      builder,
+      inputType,
+      inputTerm,
+      auxGrouping,
+      aggregates,
+      aggCallToAggFunction,
+      argsMapping,
+      aggBuffMapping,
+      currentAggBufferTerm,
+      aggBufferRowType)
+
+    val outputExpr = genHashAggOutputExpr(
+      isMerge,
+      isFinal,
+      ctx,
+      config,
+      builder,
+      auxGrouping,
+      aggregates,
+      argsMapping,
+      aggBuffMapping,
+      outputTerm,
+      outputType,
+      inputTerm,
+      inputType,
+      Some(groupKeyTerm),
+      aggBufferTerm,
+      aggBufferRowType)
+
+    (initedAggBuffer, aggregate, outputExpr)
+  }
+
+  private[flink] def buildAggregateAggBuffMapping(
+      aggBufferTypes: Array[Array[InternalType]]): Array[Array[(Int, InternalType)]] = {
+    var aggBuffOffset = 0
+    val mapping = for (aggIndex <- aggBufferTypes.indices) yield {
+      val types = aggBufferTypes(aggIndex)
+      val indexes = (aggBuffOffset until aggBuffOffset + types.length).toArray
+      aggBuffOffset += types.length
+      indexes.zip(types)
+    }
+    mapping.toArray
+  }
+
+  /**
+    * Generate codes which will init the empty agg buffer.
+    */
+  private[flink] def genReusableEmptyAggBuffer(
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      inputTerm: String,
+      inputType: RowType,
+      auxGrouping: Array[Int],
+      aggregates: Seq[UserDefinedFunction],
+      aggBufferType: RowType): GeneratedExpression = {
+    val exprCodegen = new ExprCodeGenerator(ctx, false)
+        .bindInput(inputType, inputTerm = inputTerm, inputFieldMapping = Some(auxGrouping))
+
+    val initAuxGroupingExprs = auxGrouping.map { idx =>
+      GenerateUtils.generateFieldAccess(ctx, inputType, inputTerm, idx)
+    }
+
+    val initAggCallBufferExprs = aggregates.flatMap(a =>
+      a.asInstanceOf[DeclarativeAggregateFunction].initialValuesExpressions)
+        .map(_.accept(new RexNodeConverter(builder)))
+        .map(exprCodegen.generateExpression)
+
+    val initAggBufferExprs = initAuxGroupingExprs ++ initAggCallBufferExprs
+
+    // empty agg buffer and writer will be reused
+    val emptyAggBufferTerm = CodeGenUtils.newName("emptyAggBuffer")
+    val emptyAggBufferWriterTerm = CodeGenUtils.newName("emptyAggBufferWriterTerm")
+    exprCodegen.generateResultExpression(
+      initAggBufferExprs,
+      aggBufferType,
+      classOf[BinaryRow],
+      emptyAggBufferTerm,
+      Some(emptyAggBufferWriterTerm)
+    )
+  }
+
+  private[flink] def genAggregate(
+      isMerge: Boolean,
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      inputType: RowType,
+      inputTerm: String,
+      auxGrouping: Array[Int],
+      aggregates: Seq[UserDefinedFunction],
+      aggCallToAggFunction: Seq[(AggregateCall, UserDefinedFunction)],
+      argsMapping: Array[Array[(Int, InternalType)]],
+      aggBuffMapping: Array[Array[(Int, InternalType)]],
+      currentAggBufferTerm: String,
+      aggBufferRowType: RowType): GeneratedExpression = {
+    if (isMerge) {
+      genMergeAggBuffer(
+        ctx,
+        config,
+        builder,
+        inputTerm,
+        inputType,
+        currentAggBufferTerm,
+        auxGrouping,
+        aggregates,
+        argsMapping,
+        aggBuffMapping,
+        aggBufferRowType)
+    } else {
+      genAccumulateAggBuffer(
+        ctx,
+        config,
+        builder,
+        inputTerm,
+        inputType,
+        currentAggBufferTerm,
+        auxGrouping,
+        aggCallToAggFunction,
+        argsMapping,
+        aggBuffMapping,
+        aggBufferRowType)
+    }
+  }
+
+  private[flink] def genHashAggOutputExpr(
+      isMerge: Boolean,
+      isFinal: Boolean,
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      auxGrouping: Array[Int],
+      aggregates: Seq[UserDefinedFunction],
+      argsMapping: Array[Array[(Int, InternalType)]],
+      aggBuffMapping: Array[Array[(Int, InternalType)]],
+      outputTerm: String,
+      outputType: RowType,
+      inputTerm: String,
+      inputType: RowType,
+      groupKeyTerm: Option[String],
+      aggBufferTerm: String,
+      aggBufferType: RowType): GeneratedExpression = {
+    // gen code to get agg result
+    val exprCodegen = new ExprCodeGenerator(ctx, false)
+        .bindInput(inputType, inputTerm = inputTerm)
+        .bindSecondInput(aggBufferType, inputTerm = aggBufferTerm)
+    val resultExpr = if (isFinal) {
+      val bindRefOffset = inputType.getArity
+      val getAuxGroupingExprs = auxGrouping.indices.map { idx =>
+        val (_, resultType) = aggBuffMapping(idx)(0)
+        new ResolvedAggInputReference("aux_group", bindRefOffset + idx, resultType)
+      }.map(_.accept(new RexNodeConverter(builder))).map(exprCodegen.generateExpression)
+
+      val getAggValueExprs = aggregates.zipWithIndex.map {
+        case (agg: DeclarativeAggregateFunction, aggIndex) =>
+          val idx = auxGrouping.length + aggIndex
+          agg.getValueExpression.accept(
+            ResolveReference(ctx, isMerge, bindRefOffset, agg, idx, argsMapping, aggBuffMapping))
+      }.map(_.accept(new RexNodeConverter(builder))).map(exprCodegen.generateExpression)
+
+      val getValueExprs = getAuxGroupingExprs ++ getAggValueExprs
+      val aggValueTerm = CodeGenUtils.newName("aggVal")
+      val valueType = new RowType(getValueExprs.map(_.resultType): _*)
+      exprCodegen.generateResultExpression(
+        getValueExprs,
+        valueType,
+        classOf[GenericRow],
+        aggValueTerm)
+    } else {
+      new GeneratedExpression(aggBufferTerm, "false", "", aggBufferType)
+    }
+    // add grouping keys if exists
+    groupKeyTerm match {
+      case Some(key) =>
+        val output =
+          s"""
+             |${resultExpr.code}
+             |$outputTerm.replace($key, ${resultExpr.resultTerm});
+         """.stripMargin
+        new GeneratedExpression(outputTerm, "false", output, outputType)
+      case _ => resultExpr
+    }
+  }
+
+  /**
+    * Resolves the given expression to a resolved Expression.
+    *
+    * @param isMerge this is called from merge() method
+    */
+  private case class ResolveReference(
+      ctx: CodeGeneratorContext,
+      isMerge: Boolean,
+      offset: Int,
+      agg: DeclarativeAggregateFunction,
+      aggIndex: Int,
+      argsMapping: Array[Array[(Int, InternalType)]],
+      aggBuffMapping: Array[Array[(Int, InternalType)]]) extends ExpressionVisitor[Expression] {
+
+    override def visitCall(call: CallExpression): Expression = {
+      new CallExpression(
+        call.getFunctionDefinition,
+        call.getChildren.map(_.accept(this)))
+    }
+
+    override def visitSymbol(symbolExpression: SymbolExpression): Expression = {
+      symbolExpression
+    }
+
+    override def visitValueLiteral(valueLiteralExpression: ValueLiteralExpression): Expression = {
+      valueLiteralExpression
+    }
+
+    override def visitFieldReference(input: FieldReferenceExpression): Expression = {
+      input
+    }
+
+    override def visitTypeLiteral(typeLiteral: TypeLiteralExpression): Expression = {
+      typeLiteral
+    }
+
+    private def visitUnresolvedFieldReference(
+        input: UnresolvedFieldReferenceExpression): Expression = {
+      agg.aggBufferAttributes.indexOf(input) match {
+        case -1 =>
+          // We always use UnresolvedFieldReference to represent reference of input field.
+          // In non-merge case, the input is operand of the aggregate function. But in merge
+          // case, the input is aggregate buffers which sent by local aggregate.
+          val localIndex =
+            if (isMerge) agg.mergeOperands.indexOf(input) else agg.operands.indexOf(input)
+          val (inputIndex, inputType) = argsMapping(aggIndex)(localIndex)
+          new ResolvedAggInputReference(input.getName, inputIndex, inputType)
+        case localIndex =>
+          val (aggBuffAttrIndex, aggBuffAttrType) = aggBuffMapping(aggIndex)(localIndex)
+          new ResolvedAggInputReference(
+            input.getName, offset + aggBuffAttrIndex, aggBuffAttrType)
+      }
+    }
+
+    override def visit(other: Expression): Expression = {
+      other match {
+        case u : UnresolvedFieldReferenceExpression => visitUnresolvedFieldReference(u)
+        case _ => other
+      }
+    }
+  }
+
+  /**
+    * Generate codes which will read input,
+    * merge aggregate buffers and update the aggregation map
+    */
+  private[flink] def genMergeAggBuffer(
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      inputTerm: String,
+      inputType: RowType,
+      currentAggBufferTerm: String,
+      auxGrouping: Array[Int],
+      aggregates: Seq[UserDefinedFunction],
+      argsMapping: Array[Array[(Int, InternalType)]],
+      aggBuffMapping: Array[Array[(Int, InternalType)]],
+      aggBufferType: RowType): GeneratedExpression = {
+    val exprCodegen = new ExprCodeGenerator(ctx, false)
+        .bindInput(inputType, inputTerm = inputTerm)
+        .bindSecondInput(aggBufferType, inputTerm = currentAggBufferTerm)
+
+    val mergeExprs = aggregates.zipWithIndex.flatMap {
+      case (agg: DeclarativeAggregateFunction, aggIndex) =>
+        val idx = auxGrouping.length + aggIndex
+        val bindRefOffset = inputType.getArity
+        agg.mergeExpressions.map(
+          _.accept(ResolveReference(
+            ctx, isMerge = true, bindRefOffset, agg, idx, argsMapping, aggBuffMapping)))
+    }.map(_.accept(new RexNodeConverter(builder))).map(exprCodegen.generateExpression)
+
+    val aggBufferTypeWithoutAuxGrouping = if (auxGrouping.nonEmpty) {
+      // auxGrouping does not need merge-code
+      new RowType(
+        aggBufferType.getFieldTypes.slice(auxGrouping.length, aggBufferType.getArity),
+        aggBufferType.getFieldNames.slice(auxGrouping.length, aggBufferType.getArity))
+    } else {
+      aggBufferType
+    }
+
+    val mergeExprIdxToOutputRowPosMap = mergeExprs.indices.map{
+      i => i -> (i + auxGrouping.length)
+    }.toMap
+
+    // update agg buff in-place
+    exprCodegen.generateResultExpression(
+      mergeExprs,
+      mergeExprIdxToOutputRowPosMap,
+      aggBufferTypeWithoutAuxGrouping,
+      classOf[BinaryRow],
+      outRow = currentAggBufferTerm,
+      outRowWriter = None,
+      reusedOutRow = true,
+      outRowAlreadyExists = true
+    )
+  }
+
+  /**
+    * Generate codes which will read input,
+    * accumulating aggregate buffers and updating the aggregation map
+    */
+  private[flink] def genAccumulateAggBuffer(
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      inputTerm: String,
+      inputType: RowType,
+      currentAggBufferTerm: String,
+      auxGrouping: Array[Int],
+      aggCallToAggFunction: Seq[(AggregateCall, UserDefinedFunction)],
+      argsMapping: Array[Array[(Int, InternalType)]],
+      aggBuffMapping: Array[Array[(Int, InternalType)]],
+      aggBufferType: RowType): GeneratedExpression = {
+    val exprCodegen = new ExprCodeGenerator(ctx, false)
+        .bindInput(inputType, inputTerm = inputTerm)
+        .bindSecondInput(aggBufferType, inputTerm = currentAggBufferTerm)
+
+    val accumulateExprsWithFilterArgs = aggCallToAggFunction.zipWithIndex.flatMap {
+      case (aggCallToAggFun, aggIndex) =>
+        val idx = auxGrouping.length + aggIndex
+        val bindRefOffset = inputType.getArity
+        val aggCall = aggCallToAggFun._1
+        aggCallToAggFun._2 match {
+          case agg: DeclarativeAggregateFunction =>
+            agg.accumulateExpressions.map(
+              _.accept(ResolveReference(
+                ctx, isMerge = false, bindRefOffset, agg, idx, argsMapping, aggBuffMapping))
+            ).map(e => (e, aggCall))
+        }
+    }.map {
+      case (expr: Expression, aggCall: AggregateCall) =>
+        (exprCodegen.generateExpression(expr.accept(new RexNodeConverter(builder))),
+            aggCall.filterArg)
+    }
+
+    // update agg buff in-place
+    val code = accumulateExprsWithFilterArgs.zipWithIndex.map({
+      case ((accumulateExpr, filterArg), index) =>
+        val idx = auxGrouping.length + index
+        val t = aggBufferType.getTypeAt(idx)
+        val writeCode = binaryRowFieldSetAccess(
+          idx, currentAggBufferTerm, t, accumulateExpr.resultTerm)
+        val innerCode = if (config.getNullCheck) {
+          s"""
+             |${accumulateExpr.code}
+             |if (${accumulateExpr.nullTerm}) {
+             |  ${binaryRowSetNull(idx, currentAggBufferTerm, t)};
+             |} else {
+             |  $writeCode;
+             |}
+             |""".stripMargin.trim
+        }
+        else {
+          s"""
+             |${accumulateExpr.code}
+             |$writeCode;
+             |""".stripMargin.trim
+        }
+
+        if (filterArg >= 0) {
+          s"""
+             |if ($inputTerm.getBoolean($filterArg)) {
+             | $innerCode
+             |}
+          """.stripMargin
+        } else {
+          innerCode
+        }
+
+    }) mkString "\n"
+
+    GeneratedExpression(currentAggBufferTerm, "false", code, aggBufferType)
+  }
+
+  /**
+    * Generate codes which will read aggregation map,
+    * get the aggregate values
+    */
+  private[flink] def genAggMapIterationAndOutput(
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      isFinal: Boolean,
+      aggregateMapTerm: String,
+      reuseAggMapEntryTerm: String,
+      reuseAggBufferTerm: String,
+      outputExpr: GeneratedExpression): String = {
+    // gen code to iterating the aggregate map and output to downstream
+    val inputUnboxingCode =
+      if (isFinal) s"${ctx.reuseInputUnboxingCode(reuseAggBufferTerm)}" else ""
+
+    val iteratorTerm = CodeGenUtils.newName("iterator")
+    val mapEntryTypeTerm = classOf[BytesHashMap.Entry].getCanonicalName
+    s"""
+       |org.apache.flink.util.MutableObjectIterator<$mapEntryTypeTerm> $iteratorTerm =
+       |  $aggregateMapTerm.getEntryIterator();
+       |while ($iteratorTerm.next($reuseAggMapEntryTerm) != null) {
+       |   // set result and output
+       |   $inputUnboxingCode
+       |   ${outputExpr.code}
+       |   ${OperatorCodeGenerator.generateCollect(outputExpr.resultTerm)}
+       |}
+       """.stripMargin
+  }
+
+  private[flink] def genRetryAppendToMap(
+      aggregateMapTerm: String,
+      currentKeyTerm: String,
+      initedAggBuffer: GeneratedExpression,
+      lookupInfo: String,
+      currentAggBufferTerm: String): String = {
+    s"""
+       | // reset aggregate map retry append
+       |$aggregateMapTerm.reset();
+       |$lookupInfo = $aggregateMapTerm.lookup($currentKeyTerm);
+       |try {
+       |  $currentAggBufferTerm =
+       |    $aggregateMapTerm.append($lookupInfo, ${initedAggBuffer.resultTerm});
+       |} catch (java.io.EOFException e) {
+       |  throw new OutOfMemoryError("BytesHashMap Out of Memory.");
+       |}
+       """.stripMargin
+  }
+
+  private[flink] def genAggMapOOMHandling(
+      isFinal: Boolean,
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      groupingAndAuxGrouping: (Array[Int], Array[Int]),
+      aggCallToAggFunction: Seq[(AggregateCall, UserDefinedFunction)],
+      aggArgs: Array[Array[Int]],
+      aggregates: Seq[UserDefinedFunction],
+      udaggs: Map[AggregateFunction[_, _], String],
+      logTerm: String,
+      aggregateMapTerm: String,
+      aggMapKVTypesTerm: (String, String),
+      aggMapKVRowType: (RowType, RowType),
+      aggBufferNames: Array[Array[String]],
+      aggBufferTypes: Array[Array[InternalType]],
+      outputTerm: String,
+      outputType: RowType,
+      outputResultFromMap: String,
+      sorterTerm: String,
+      retryAppend: String): (String, String) = {
+    val (grouping, auxGrouping) = groupingAndAuxGrouping
+    if (isFinal) {
+      val logMapSpilling =
+        CodeGenUtils.genLogInfo(
+          logTerm, s"BytesHashMap out of memory with {} entries, start spilling.",
+          s"$aggregateMapTerm.getNumElements()")
+
+      // gen fallback to sort agg
+      val (groupKeyTypesTerm, aggBufferTypesTerm) = aggMapKVTypesTerm
+      val (groupKeyRowType, aggBufferRowType) =  aggMapKVRowType
+      prepareFallbackSorter(ctx, sorterTerm)
+      val createSorter = genCreateFallbackSorter(
+        ctx, groupKeyRowType, groupKeyTypesTerm, aggBufferTypesTerm, sorterTerm)
+      val fallbackToSortAggCode = genFallbackToSortAgg(
+        ctx,
+        config,
+        builder,
+        grouping,
+        auxGrouping,
+        aggCallToAggFunction,
+        aggArgs,
+        aggregates,
+        udaggs,
+        aggregateMapTerm,
+        (groupKeyRowType, aggBufferRowType),
+        aggregateMapTerm,
+        sorterTerm,
+        outputTerm,
+        outputType,
+        aggBufferNames,
+        aggBufferTypes)
+
+      val memPoolTypeTerm = classOf[BytesHashMapSpillMemorySegmentPool].getName
+      val dealWithAggHashMapOOM =
+        s"""
+           |$logMapSpilling
+           | // hash map out of memory, spill to external sorter
+           |if ($sorterTerm == null) {
+           |  $createSorter
+           |}
+           | // sort and spill
+           |$sorterTerm.sortAndSpill(
+           |  $aggregateMapTerm.getRecordAreaMemorySegments(),
+           |  $aggregateMapTerm.getNumElements(),
+           |  new $memPoolTypeTerm($aggregateMapTerm.getBucketAreaMemorySegments()));
+           | // retry append
+           |$retryAppend
+       """.stripMargin
+      (dealWithAggHashMapOOM, fallbackToSortAggCode)
+    } else {
+      val logMapOutput =
+        CodeGenUtils.genLogInfo(
+          logTerm, s"BytesHashMap out of memory with {} entries, output directly.",
+          s"$aggregateMapTerm.getNumElements()")
+
+      val dealWithAggHashMapOOM =
+        s"""
+           |$logMapOutput
+           | // hash map out of memory, output directly
+           |$outputResultFromMap
+           | // retry append
+           |$retryAppend
+          """.stripMargin
+      (dealWithAggHashMapOOM, "")
+    }
+  }
+
+  private[flink] def prepareFallbackSorter(ctx: CodeGeneratorContext, sorterTerm: String): Unit = {
+    val sorterTypeTerm = classOf[BufferedKVExternalSorter].getName
+    ctx.addReusableMember(s"transient $sorterTypeTerm $sorterTerm;")
+    ctx.addReusableCloseStatement(s"if ($sorterTerm != null) $sorterTerm.close();")
+  }
+
+  private[flink] def prepareMetrics(
+      ctx: CodeGeneratorContext, hashTerm: String, sorterTerm: String): Unit = {
+    val gauge = classOf[Gauge[_]].getCanonicalName
+    val longType = classOf[java.lang.Long].getCanonicalName
+
+    val numSpillFiles =
+      s"""
+         |getMetricGroup().gauge("numSpillFiles", new $gauge<$longType>() {
+         | @Override
+         | public $longType getValue() {
+         |  return $hashTerm.getNumSpillFiles();
+         |  }
+         | });
+       """.stripMargin.trim
+
+    val memoryUsedSizeInBytes =
+      s"""
+         |getMetricGroup().gauge("memoryUsedSizeInBytes", new $gauge<$longType>() {
+         | @Override
+         | public $longType getValue() {
+         |  return $hashTerm.getUsedMemoryInBytes();
+         |  }
+         | });
+       """.stripMargin.trim
+    ctx.addReusableOpenStatement(numSpillFiles)
+    ctx.addReusableOpenStatement(memoryUsedSizeInBytes)
+
+    if (sorterTerm != null) {
+      val spillInBytes =
+        s"""
+           | getMetricGroup().gauge("spillInBytes", new $gauge<$longType>() {
+           |  @Override
+           |  public $longType getValue() {
+           |    return $hashTerm.getSpillInBytes();
+           |   }
+           |});
+       """.stripMargin.trim
+      ctx.addReusableOpenStatement(spillInBytes)
+    }
+  }
+
+  private[flink] def genCreateFallbackSorter(
+      ctx: CodeGeneratorContext,
+      groupKeyRowType: RowType,
+      groupKeyTypesTerm: String,
+      aggBufferTypesTerm: String,
+      sorterTerm: String): String = {
+    val keyComputerTerm = CodeGenUtils.newName("keyComputer")
+    val recordComparatorTerm = CodeGenUtils.newName("recordComparator")
+    val prepareSorterCode = genKVSorterPrepareCode(
+      ctx, keyComputerTerm, recordComparatorTerm, groupKeyRowType)
+
+    val binaryRowSerializerTypeTerm = classOf[BinaryRowSerializer].getName
+    val sorterTypeTerm = classOf[BufferedKVExternalSorter].getName
+    s"""
+       |  $prepareSorterCode
+       |  $sorterTerm = new $sorterTypeTerm(
+       |    getContainingTask().getEnvironment().getIOManager(),
+       |    new $binaryRowSerializerTypeTerm($groupKeyTypesTerm.length),
+       |    new $binaryRowSerializerTypeTerm($aggBufferTypesTerm.length),
+       |    $keyComputerTerm, $recordComparatorTerm,
+       |    getContainingTask().getEnvironment().getMemoryManager().getPageSize(),
+       |    getContainingTask().getJobConfiguration()
+       |  );
+       """.stripMargin
+  }
+
+  private[flink] def genFallbackToSortAgg(
+      ctx: CodeGeneratorContext,
+      config: TableConfig,
+      builder: RelBuilder,
+      grouping: Array[Int],
+      auxGrouping: Array[Int],
+      aggCallToAggFunction: Seq[(AggregateCall, UserDefinedFunction)],
+      aggArgs: Array[Array[Int]],
+      aggregates: Seq[UserDefinedFunction],
+      udaggs: Map[AggregateFunction[_, _], String],
+      mapTerm: String,
+      mapKVRowTypes: (RowType, RowType),
+      aggregateMapTerm: String,
+      sorterTerm: String,
+      outputTerm: String,
+      outputType: RowType,
+      aggBufferNames: Array[Array[String]],
+      aggBufferTypes: Array[Array[InternalType]]): String = {
+    val (groupKeyRowType, aggBufferRowType) = mapKVRowTypes
+    val keyTerm = CodeGenUtils.newName("key")
+    val lastKeyTerm = CodeGenUtils.newName("lastKey")
+    val keyNotEquals = AggCodeGenHelper.genGroupKeyChangedCheckCode(keyTerm, lastKeyTerm)
+
+    val joinedRow = classOf[JoinedRow].getName
+    val fallbackInputTerm = ctx.addReusableLocalVariable(joinedRow, "fallbackInput")
+    val fallbackInputType = new RowType(
+      groupKeyRowType.getFieldTypes ++ aggBufferRowType.getFieldTypes,
+      groupKeyRowType.getFieldNames ++ aggBufferRowType.getFieldNames)
+
+    val (initAggBufferCode, updateAggBufferCode, resultExpr) = AggCodeGenHelper.genSortAggCodes(
+      isMerge = true,
+      isFinal = true,
+      ctx,
+      config,
+      builder,
+      grouping,
+      auxGrouping,
+      aggCallToAggFunction,
+      aggArgs,
+      aggregates,
+      udaggs,
+      fallbackInputTerm,
+      fallbackInputType,
+      aggBufferNames,
+      aggBufferTypes,
+      outputType,
+      forHashAgg = true)
+
+    val kvPairTerm = CodeGenUtils.newName("kvPair")
+    val kvPairTypeTerm = classOf[JTuple2[BinaryRow, BinaryRow]].getName
+    val aggBuffTerm = CodeGenUtils.newName("val")
+    val binaryRow = classOf[BinaryRow].getName
+
+    s"""
+       |  $binaryRow $lastKeyTerm = null;
+       |  $kvPairTypeTerm<$binaryRow, $binaryRow> $kvPairTerm = null;
+       |  $binaryRow $keyTerm = null;
+       |  $binaryRow $aggBuffTerm = null;
+       |  $fallbackInputTerm = new $joinedRow();
+       |
+       |  // free hash map memory, but not release back to memory manager
+       |
+       |  org.apache.flink.util.MutableObjectIterator<$kvPairTypeTerm<$binaryRow, $binaryRow>>
+       |    iterator = $sorterTerm.getKVIterator();
+       |
+       |  while (
+       |    ($kvPairTerm = ($kvPairTypeTerm<$binaryRow, $binaryRow>) iterator.next()) != null) {
+       |    $keyTerm = ($binaryRow) $kvPairTerm.f0;
+       |    $aggBuffTerm = ($binaryRow) $kvPairTerm.f1;
+       |    // prepare input
+       |    $fallbackInputTerm.replace($keyTerm, $aggBuffTerm);
+       |    if ($lastKeyTerm == null) {
+       |      // found first key group
+       |      $lastKeyTerm = $keyTerm.copy();
+       |      $initAggBufferCode
+       |    } else if ($keyNotEquals) {
+       |      // output current group aggregate result
+       |      ${resultExpr.code}
+       |      $outputTerm.replace($lastKeyTerm, ${resultExpr.resultTerm});
+       |      ${OperatorCodeGenerator.generateCollect(outputTerm)}
+       |      // found new group
+       |      $lastKeyTerm = $keyTerm.copy();
+       |      $initAggBufferCode
+       |    }
+       |    // reusable field access codes for agg buffer merge
+       |    ${ctx.reuseInputUnboxingCode(fallbackInputTerm)}
+       |    // merge aggregate map's value into aggregate buffer fields
+       |    $updateAggBufferCode
+       |  }
+       |
+       |  // output last key group aggregate result
+       |  ${resultExpr.code}
+       |  $outputTerm.replace($lastKeyTerm, ${resultExpr.resultTerm});
+       |  ${OperatorCodeGenerator.generateCollect(outputTerm)}
+       """.stripMargin
+  }
+
+  private[flink] def genKVSorterPrepareCode(
+      ctx: CodeGeneratorContext,
+      keyComputerTerm: String,
+      recordComparatorTerm: String,
+      aggMapKeyType: RowType) : String = {
+    val keyFieldTypes = aggMapKeyType.getFieldTypes
+    val keys = keyFieldTypes.indices.toArray
+    val orders = keys.map((_) => true)
+    val nullsIsLast = FlinkPlannerImpl.getNullDefaultOrders(orders)
+
+    val sortCodeGenerator = new SortCodeGenerator(
+      ctx.tableConfig, keys, keyFieldTypes, orders, nullsIsLast)
+    val computer = sortCodeGenerator.generateNormalizedKeyComputer("AggMapKeyComputer")
+    val comparator = sortCodeGenerator.generateRecordComparator("AggMapValueComparator")
+
+    val keyComputerTypeTerm = classOf[NormalizedKeyComputer].getName
+    val keyComputeInnerClassTerm = computer.getClassName
+    val recordComparatorTypeTerm = classOf[RecordComparator].getName
+    val recordComparatorInnerClassTerm = comparator.getClassName
+    ctx.addReusableInnerClass(keyComputeInnerClassTerm, computer.getCode)
+    ctx.addReusableInnerClass(recordComparatorInnerClassTerm, comparator.getCode)
+
+    val computerRefs = ctx.addReusableObject(computer.getReferences, "computerRefs")
+    val comparatorRefs = ctx.addReusableObject(comparator.getReferences, "comparatorRefs")
+
+    s"""
+       |  $keyComputerTypeTerm $keyComputerTerm = new $keyComputeInnerClassTerm($computerRefs);
+       |  $recordComparatorTypeTerm $recordComparatorTerm =
+       |    new $recordComparatorInnerClassTerm($comparatorRefs);
+       |""".stripMargin
+  }
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/HashAggCodeGenerator.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/HashAggCodeGenerator.scala
new file mode 100644
index 0000000..04d869b
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/HashAggCodeGenerator.scala
@@ -0,0 +1,239 @@
+/*
+ * 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.codegen.agg.batch
+
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator
+import org.apache.flink.table.`type`.RowType
+import org.apache.flink.table.codegen.{CodeGenUtils, CodeGeneratorContext, ProjectionCodeGenerator}
+import org.apache.flink.table.dataformat.{BaseRow, BinaryRow, GenericRow, JoinedRow}
+import org.apache.flink.table.functions.{DeclarativeAggregateFunction, UserDefinedFunction}
+import org.apache.flink.table.generated.GeneratedOperator
+import org.apache.flink.table.plan.util.AggregateInfoList
+import org.apache.flink.table.runtime.TableStreamOperator
+import org.apache.flink.table.runtime.aggregate.{BytesHashMap, BytesHashMapSpillMemorySegmentPool}
+
+import org.apache.calcite.tools.RelBuilder
+
+/**
+  * Operator code generator for HashAggregation, Only deal with [[DeclarativeAggregateFunction]]
+  * and aggregateBuffers should be update(e.g.: setInt) in [[BinaryRow]].
+  * (Hash Aggregate performs much better than Sort Aggregate).
+  */
+class HashAggCodeGenerator(
+    ctx: CodeGeneratorContext,
+    builder: RelBuilder,
+    aggInfoList: AggregateInfoList,
+    inputType: RowType,
+    outputType: RowType,
+    grouping: Array[Int],
+    auxGrouping: Array[Int],
+    isMerge: Boolean,
+    isFinal: Boolean) {
+
+  private lazy val groupKeyRowType = AggCodeGenHelper.projectRowType(inputType, grouping)
+  private lazy val aggCallToAggFunction =
+    aggInfoList.aggInfos.map(info => (info.agg, info.function))
+  private lazy val aggregateCalls = aggCallToAggFunction.map(_._1)
+  private lazy val aggregates: Seq[UserDefinedFunction] = aggInfoList.aggInfos.map(_.function)
+  private lazy val aggArgs: Array[Array[Int]] = aggInfoList.aggInfos.map(_.argIndexes)
+  // get udagg instance names
+  private lazy val udaggs = AggCodeGenHelper.getUdaggs(aggregates)
+  // currently put auxGrouping to aggBuffer in code-gen
+  private lazy val aggBufferNames = AggCodeGenHelper.getAggBufferNames(auxGrouping, aggregates)
+  private lazy val aggBufferTypes =
+    AggCodeGenHelper.getAggBufferTypes(inputType, auxGrouping, aggregates)
+  private lazy val aggBufferRowType = new RowType(aggBufferTypes.flatten, aggBufferNames.flatten)
+
+  def genWithKeys(
+      reservedManagedMemory: Long, maxManagedMemory: Long)
+    : GeneratedOperator[OneInputStreamOperator[BaseRow, BaseRow]] = {
+    val config = ctx.tableConfig
+    val inputTerm = CodeGenUtils.DEFAULT_INPUT1_TERM
+    val className = if (isFinal) "HashAggregateWithKeys" else "LocalHashAggregateWithKeys"
+
+    // add logger
+    val logTerm = CodeGenUtils.newName("LOG")
+    ctx.addReusableLogger(logTerm, className)
+
+    // gen code to do group key projection from input
+    val currentKeyTerm = CodeGenUtils.newName("currentKey")
+    val currentKeyWriterTerm = CodeGenUtils.newName("currentKeyWriter")
+    val keyProjectionCode = ProjectionCodeGenerator.generateProjectionExpression(
+      ctx,
+      inputType,
+      groupKeyRowType,
+      grouping,
+      inputTerm = inputTerm,
+      outRecordTerm = currentKeyTerm,
+      outRecordWriterTerm = currentKeyWriterTerm).code
+
+    // gen code to create groupKey, aggBuffer Type array
+    // it will be used in BytesHashMap and BufferedKVExternalSorter if enable fallback
+    val groupKeyTypesTerm = CodeGenUtils.newName("groupKeyTypes")
+    val aggBufferTypesTerm = CodeGenUtils.newName("aggBufferTypes")
+    HashAggCodeGenHelper.prepareHashAggKVTypes(
+      ctx, groupKeyTypesTerm, aggBufferTypesTerm, groupKeyRowType, aggBufferRowType)
+
+    // gen code to aggregate and output using hash map
+    val aggregateMapTerm = CodeGenUtils.newName("aggregateMap")
+    val lookupInfo = ctx.addReusableLocalVariable(
+      classOf[BytesHashMap.LookupInfo].getCanonicalName,
+      "lookupInfo")
+    HashAggCodeGenHelper.prepareHashAggMap(
+      ctx,
+      config,
+      reservedManagedMemory,
+      maxManagedMemory,
+      groupKeyTypesTerm,
+      aggBufferTypesTerm,
+      aggregateMapTerm)
+
+    val outputTerm = CodeGenUtils.newName("hashAggOutput")
+    val (reuseAggMapEntryTerm, reuseGroupKeyTerm, reuseAggBufferTerm) =
+      HashAggCodeGenHelper.prepareTermForAggMapIteration(
+        ctx,
+        outputTerm,
+        outputType,
+        groupKeyRowType,
+        aggBufferRowType,
+        if (grouping.isEmpty) classOf[GenericRow] else classOf[JoinedRow])
+
+    val currentAggBufferTerm = ctx.addReusableLocalVariable(
+      classOf[BinaryRow].getName, "currentAggBuffer")
+    val (initedAggBuffer, aggregate, outputExpr) = HashAggCodeGenHelper.genHashAggCodes(
+      isMerge,
+      isFinal,
+      ctx,
+      config,
+      builder,
+      (grouping, auxGrouping),
+      inputTerm,
+      inputType,
+      aggregateCalls,
+      aggCallToAggFunction,
+      aggArgs,
+      aggregates,
+      currentAggBufferTerm,
+      aggBufferRowType,
+      aggBufferNames,
+      aggBufferTypes,
+      outputTerm,
+      outputType,
+      reuseGroupKeyTerm,
+      reuseAggBufferTerm)
+
+    val outputResultFromMap = HashAggCodeGenHelper.genAggMapIterationAndOutput(
+      ctx, config, isFinal, aggregateMapTerm, reuseAggMapEntryTerm, reuseAggBufferTerm, outputExpr)
+
+    // gen code to deal with hash map oom, if enable fallback we will use sort agg strategy
+    val sorterTerm = CodeGenUtils.newName("sorter")
+    val retryAppend = HashAggCodeGenHelper.genRetryAppendToMap(
+      aggregateMapTerm, currentKeyTerm, initedAggBuffer, lookupInfo, currentAggBufferTerm)
+
+    val (dealWithAggHashMapOOM, fallbackToSortAggCode) = HashAggCodeGenHelper.genAggMapOOMHandling(
+      isFinal,
+      ctx,
+      config,
+      builder,
+      (grouping, auxGrouping),
+      aggCallToAggFunction,
+      aggArgs,
+      aggregates,
+      udaggs,
+      logTerm,
+      aggregateMapTerm,
+      (groupKeyTypesTerm, aggBufferTypesTerm),
+      (groupKeyRowType, aggBufferRowType),
+      aggBufferNames,
+      aggBufferTypes,
+      outputTerm,
+      outputType,
+      outputResultFromMap,
+      sorterTerm,
+      retryAppend)
+
+    HashAggCodeGenHelper.prepareMetrics(ctx, aggregateMapTerm, if (isFinal) sorterTerm else null)
+
+    val lazyInitAggBufferCode = if (auxGrouping.nonEmpty) {
+      s"""
+         |// lazy init agg buffer (with auxGrouping)
+         |${initedAggBuffer.code}
+       """.stripMargin
+    } else {
+      ""
+    }
+
+    val processCode =
+      s"""
+         | // input field access for group key projection and aggregate buffer update
+         |${ctx.reuseInputUnboxingCode(inputTerm)}
+         | // project key from input
+         |$keyProjectionCode
+         | // look up output buffer using current group key
+         |$lookupInfo = $aggregateMapTerm.lookup($currentKeyTerm);
+         |$currentAggBufferTerm = $lookupInfo.getValue();
+         |
+         |if (!$lookupInfo.isFound()) {
+         |  $lazyInitAggBufferCode
+         |  // append empty agg buffer into aggregate map for current group key
+         |  try {
+         |    $currentAggBufferTerm =
+         |      $aggregateMapTerm.append($lookupInfo, ${initedAggBuffer.resultTerm});
+         |  } catch (java.io.EOFException exp) {
+         |    $dealWithAggHashMapOOM
+         |  }
+         |}
+         | // aggregate buffer fields access
+         |${ctx.reuseInputUnboxingCode(currentAggBufferTerm)}
+         | // do aggregate and update agg buffer
+         |${aggregate.code}
+         |""".stripMargin.trim
+
+    val endInputCode = if (isFinal) {
+      val memPoolTypeTerm = classOf[BytesHashMapSpillMemorySegmentPool].getName
+      s"""
+         |if ($sorterTerm == null) {
+         | // no spilling, output by iterating aggregate map.
+         | $outputResultFromMap
+         |} else {
+         |  // spill last part of input' aggregation output buffer
+         |  $sorterTerm.sortAndSpill(
+         |    $aggregateMapTerm.getRecordAreaMemorySegments(),
+         |    $aggregateMapTerm.getNumElements(),
+         |    new $memPoolTypeTerm($aggregateMapTerm.getBucketAreaMemorySegments()));
+         |   // only release floating memory in advance.
+         |   $aggregateMapTerm.free(true);
+         |  // fall back to sort based aggregation
+         |  $fallbackToSortAggCode
+         |}
+       """.stripMargin
+    } else {
+      s"$outputResultFromMap"
+    }
+
+    AggCodeGenHelper.generateOperator(
+      ctx,
+      className,
+      classOf[TableStreamOperator[BaseRow]].getCanonicalName,
+      processCode,
+      endInputCode,
+      inputType,
+      config)
+  }
+}
diff --git a/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/SortAggCodeGenerator.scala b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/SortAggCodeGenerator.scala
new file mode 100644
index 0000000..49edb76
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/main/scala/org/apache/flink/table/codegen/agg/batch/SortAggCodeGenerator.scala
@@ -0,0 +1,151 @@
+/*
+ * 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.codegen.agg.batch
+
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator
+import org.apache.flink.table.`type`.RowType
+import org.apache.flink.table.codegen.OperatorCodeGenerator.generateCollect
+import org.apache.flink.table.codegen.{CodeGenUtils, CodeGeneratorContext, ProjectionCodeGenerator}
+import org.apache.flink.table.dataformat.{BaseRow, BinaryRow, JoinedRow}
+import org.apache.flink.table.functions.AggregateFunction
+import org.apache.flink.table.generated.GeneratedOperator
+import org.apache.flink.table.plan.util.AggregateInfoList
+import org.apache.flink.table.runtime.TableStreamOperator
+
+import org.apache.calcite.tools.RelBuilder
+
+/**
+  * Sort aggregation code generator to deal with all aggregate functions with keys.
+  * It require input in keys order.
+  */
+object SortAggCodeGenerator {
+
+  private[flink] def genWithKeys(
+      ctx: CodeGeneratorContext,
+      builder: RelBuilder,
+      aggInfoList: AggregateInfoList,
+      inputType: RowType,
+      outputType: RowType,
+      grouping: Array[Int],
+      auxGrouping: Array[Int],
+      isMerge: Boolean,
+      isFinal: Boolean): GeneratedOperator[OneInputStreamOperator[BaseRow, BaseRow]] = {
+    val config = ctx.tableConfig
+    val inputTerm = CodeGenUtils.DEFAULT_INPUT1_TERM
+
+    val aggCallToAggFunction = aggInfoList.aggInfos.map(info => (info.agg, info.function))
+    val aggArgs = aggInfoList.aggInfos.map(_.argIndexes)
+
+    // register udaggs
+    aggCallToAggFunction.map(_._2).filter(a => a.isInstanceOf[AggregateFunction[_, _]])
+        .map(a => ctx.addReusableFunction(a))
+
+    val lastKeyTerm = "lastKey"
+    val currentKeyTerm = "currentKey"
+    val currentKeyWriterTerm = "currentKeyWriter"
+
+    val groupKeyRowType = AggCodeGenHelper.projectRowType(inputType, grouping)
+    val keyProjectionCode = ProjectionCodeGenerator.generateProjectionExpression(
+      ctx,
+      inputType,
+      groupKeyRowType,
+      grouping,
+      inputTerm = inputTerm,
+      outRecordTerm = currentKeyTerm,
+      outRecordWriterTerm = currentKeyWriterTerm).code
+
+    val keyNotEquals = AggCodeGenHelper.genGroupKeyChangedCheckCode(currentKeyTerm, lastKeyTerm)
+
+    val aggregates = aggCallToAggFunction.map(_._2)
+    val udaggs = AggCodeGenHelper.getUdaggs(aggregates)
+    val aggBufferNames = AggCodeGenHelper.getAggBufferNames(auxGrouping, aggregates)
+    val aggBufferTypes = AggCodeGenHelper.getAggBufferTypes(inputType, auxGrouping, aggregates)
+
+    val (initAggBufferCode, doAggregateCode, aggOutputExpr) = AggCodeGenHelper.genSortAggCodes(
+      isMerge,
+      isFinal,
+      ctx,
+      config,
+      builder,
+      grouping,
+      auxGrouping,
+      aggCallToAggFunction,
+      aggArgs,
+      aggregates,
+      udaggs,
+      inputTerm,
+      inputType,
+      aggBufferNames,
+      aggBufferTypes,
+      outputType)
+
+    val joinedRow = "joinedRow"
+    ctx.addReusableOutputRecord(outputType, classOf[JoinedRow], joinedRow)
+    val binaryRow = classOf[BinaryRow].getName
+    ctx.addReusableMember(s"$binaryRow $lastKeyTerm = null;")
+
+    val processCode =
+      s"""
+         |hasInput = true;
+         |${ctx.reuseInputUnboxingCode(inputTerm)}
+         |
+         |// project key from input
+         |$keyProjectionCode
+         |if ($lastKeyTerm == null) {
+         |  $lastKeyTerm = $currentKeyTerm.copy();
+         |
+         |  // init agg buffer
+         |  $initAggBufferCode
+         |} else if ($keyNotEquals) {
+         |
+         |  // write output
+         |  ${aggOutputExpr.code}
+         |
+         |  ${generateCollect(s"$joinedRow.replace($lastKeyTerm, ${aggOutputExpr.resultTerm})")}
+         |
+         |  $lastKeyTerm = $currentKeyTerm.copy();
+         |
+         |  // init agg buffer
+         |  $initAggBufferCode
+         |}
+         |
+         |// do doAggregateCode
+         |$doAggregateCode
+         |""".stripMargin.trim
+
+    val endInputCode =
+      s"""
+         |if (hasInput) {
+         |  // write last output
+         |  ${aggOutputExpr.code}
+         |  ${generateCollect(s"$joinedRow.replace($lastKeyTerm, ${aggOutputExpr.resultTerm})")}
+         |}
+       """.stripMargin
+
+    val className = if (isFinal) "SortAggregateWithKeys" else "LocalSortAggregateWithKeys"
+    AggCodeGenHelper.generateOperator(
+      ctx,
+      className,
+      classOf[TableStreamOperator[BaseRow]].getCanonicalName,
+      processCode,
+      endInputCode,
+      inputType,
+      config)
+  }
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/codegen/agg/TestLongAvgFunc.java b/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/codegen/agg/TestLongAvgFunc.java
index 802ab81..060d261 100644
--- a/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/codegen/agg/TestLongAvgFunc.java
+++ b/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/codegen/agg/TestLongAvgFunc.java
@@ -60,7 +60,7 @@ public class TestLongAvgFunc extends AggregateFunction<Double, Tuple2<Long, Long
 		if (acc.f1 == 0) {
 			return null;
 		} else {
-			return (double) (acc.f0 / acc.f1);
+			return ((double) acc.f0 / acc.f1);
 		}
 	}
 
diff --git a/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/util/BaseRowTestUtil.java b/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/util/BaseRowTestUtil.java
index d6087ef..f144000 100644
--- a/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/util/BaseRowTestUtil.java
+++ b/flink-table/flink-table-planner-blink/src/test/java/org/apache/flink/table/util/BaseRowTestUtil.java
@@ -22,6 +22,7 @@ import org.apache.flink.table.dataformat.BaseRow;
 import org.apache.flink.table.dataformat.GenericRow;
 import org.apache.flink.table.dataformat.TypeGetterSetters;
 import org.apache.flink.table.type.InternalType;
+import org.apache.flink.table.type.RowType;
 import org.apache.flink.table.typeutils.BaseRowTypeInfo;
 import org.apache.flink.util.StringUtils;
 
@@ -40,7 +41,7 @@ public class BaseRowTestUtil {
 	}
 
 	public static String baseRowToString(BaseRow value, BaseRowTypeInfo rowTypeInfo, TimeZone tz, boolean withHeader) {
-		GenericRow genericRow = toGenericRow(value, rowTypeInfo);
+		GenericRow genericRow = toGenericRowDeeply(value, rowTypeInfo.getInternalTypes());
 		return genericRowToString(genericRow, tz, withHeader);
 	}
 
@@ -67,19 +68,23 @@ public class BaseRowTestUtil {
 		return sb.toString();
 	}
 
-	private static GenericRow toGenericRow(BaseRow baseRow, BaseRowTypeInfo baseRowTypeInfo) {
+	public static GenericRow toGenericRowDeeply(BaseRow baseRow, InternalType[] types) {
 		if (baseRow instanceof GenericRow) {
 			return (GenericRow) baseRow;
 		} else {
 			int fieldNum = baseRow.getArity();
 			GenericRow row = new GenericRow(fieldNum);
 			row.setHeader(baseRow.getHeader());
-			InternalType[] internalTypes = baseRowTypeInfo.getInternalTypes();
 			for (int i = 0; i < fieldNum; i++) {
 				if (baseRow.isNullAt(i)) {
 					row.setField(i, null);
 				} else {
-					row.setField(i, TypeGetterSetters.get(baseRow, i, internalTypes[i]));
+					InternalType type = types[i];
+					Object o = TypeGetterSetters.get(baseRow, i, type);
+					if (type instanceof RowType) {
+						o = toGenericRowDeeply((BaseRow) o, ((RowType) type).getFieldTypes());
+					}
+					row.setField(i, o);
 				}
 			}
 			return row;
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/AggTestBase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/AggTestBase.scala
new file mode 100644
index 0000000..d6296b1
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/AggTestBase.scala
@@ -0,0 +1,101 @@
+/*
+ * 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.codegen.agg
+
+import org.apache.flink.api.common.functions.RuntimeContext
+import org.apache.flink.api.common.typeinfo.Types
+import org.apache.flink.streaming.api.environment.LocalStreamEnvironment
+import org.apache.flink.table.`type`.{InternalType, InternalTypes, RowType}
+import org.apache.flink.table.api.TableConfig
+import org.apache.flink.table.api.java.StreamTableEnvironment
+import org.apache.flink.table.calcite.{FlinkRelBuilder, FlinkTypeFactory, FlinkTypeSystem}
+import org.apache.flink.table.codegen.CodeGeneratorContext
+import org.apache.flink.table.dataview.DataViewSpec
+import org.apache.flink.table.functions.AvgAggFunction.{DoubleAvgAggFunction, IntegralAvgAggFunction}
+import org.apache.flink.table.plan.util.{AggregateInfo, AggregateInfoList}
+import org.apache.flink.table.runtime.context.ExecutionContext
+
+import org.apache.calcite.rel.core.AggregateCall
+import org.apache.calcite.tools.{FrameworkConfig, RelBuilder}
+import org.powermock.api.mockito.PowerMockito.{mock, when}
+
+/**
+  * Agg test base to mock agg information and etc.
+  */
+abstract class AggTestBase {
+
+  val typeFactory: FlinkTypeFactory = new FlinkTypeFactory(new FlinkTypeSystem())
+  val env = new LocalStreamEnvironment
+  val conf = new TableConfig
+  val tEnv = new StreamTableEnvironment(env, conf)
+  val frameworkConfig: FrameworkConfig = tEnv.getFrameworkConfig
+  val inputNames = Array("f0", "f1", "f2", "f3", "f4")
+  val inputTypes: Array[InternalType] = Array(
+    InternalTypes.STRING, InternalTypes.LONG, InternalTypes.DOUBLE, InternalTypes.LONG,
+    InternalTypes.STRING)
+  val inputType = new RowType(inputTypes, inputNames)
+
+  val relBuilder: RelBuilder = FlinkRelBuilder.create(frameworkConfig).values(
+    typeFactory.buildLogicalRowType(inputNames, inputTypes))
+  val aggInfo1: AggregateInfo = {
+    val aggInfo = mock(classOf[AggregateInfo])
+    val call = mock(classOf[AggregateCall])
+    when(aggInfo, "agg").thenReturn(call)
+    when(call, "getName").thenReturn("avg1")
+    when(aggInfo, "function").thenReturn(new IntegralAvgAggFunction)
+    when(aggInfo, "externalAccTypes").thenReturn(Array(Types.LONG, Types.LONG))
+    when(aggInfo, "argIndexes").thenReturn(Array(1))
+    when(aggInfo, "aggIndex").thenReturn(0)
+    aggInfo
+  }
+
+  val aggInfo2: AggregateInfo = {
+    val aggInfo = mock(classOf[AggregateInfo])
+    val call = mock(classOf[AggregateCall])
+    when(aggInfo, "agg").thenReturn(call)
+    when(call, "getName").thenReturn("avg2")
+    when(aggInfo, "function").thenReturn(new DoubleAvgAggFunction)
+    when(aggInfo, "externalAccTypes").thenReturn(Array(Types.DOUBLE, Types.LONG))
+    when(aggInfo, "argIndexes").thenReturn(Array(2))
+    when(aggInfo, "aggIndex").thenReturn(1)
+    aggInfo
+  }
+
+  val imperativeAggFunc = new TestLongAvgFunc
+  val aggInfo3: AggregateInfo = {
+    val aggInfo = mock(classOf[AggregateInfo])
+    val call = mock(classOf[AggregateCall])
+    when(aggInfo, "agg").thenReturn(call)
+    when(call, "getName").thenReturn("avg3")
+    when(aggInfo, "function").thenReturn(imperativeAggFunc)
+    when(aggInfo, "externalAccTypes").thenReturn(Array(imperativeAggFunc.getAccumulatorType))
+    when(aggInfo, "externalResultType").thenReturn(Types.DOUBLE)
+    when(aggInfo, "viewSpecs").thenReturn(Array[DataViewSpec]())
+    when(aggInfo, "argIndexes").thenReturn(Array(3))
+    when(aggInfo, "aggIndex").thenReturn(2)
+    aggInfo
+  }
+
+  val aggInfoList = AggregateInfoList(
+    Array(aggInfo1, aggInfo2, aggInfo3), None, count1AggInserted = false, Array())
+  val ctx = new CodeGeneratorContext(conf)
+  val classLoader: ClassLoader = Thread.currentThread().getContextClassLoader
+  val context: ExecutionContext = mock(classOf[ExecutionContext])
+  when(context, "getRuntimeContext").thenReturn(mock(classOf[RuntimeContext]))
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/AggsHandlerCodeGeneratorTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/AggsHandlerCodeGeneratorTest.scala
index 24d761b..1839541 100644
--- a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/AggsHandlerCodeGeneratorTest.scala
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/AggsHandlerCodeGeneratorTest.scala
@@ -18,85 +18,15 @@
 
 package org.apache.flink.table.codegen.agg
 
-import org.apache.flink.api.common.functions.RuntimeContext
 import org.apache.flink.api.common.typeinfo.Types
-import org.apache.flink.streaming.api.environment.LocalStreamEnvironment
-import org.apache.flink.table.`type`.InternalTypes
-import org.apache.flink.table.api.TableConfig
-import org.apache.flink.table.api.java.StreamTableEnvironment
-import org.apache.flink.table.calcite.{FlinkRelBuilder, FlinkTypeFactory, FlinkTypeSystem}
-import org.apache.flink.table.codegen.CodeGeneratorContext
 import org.apache.flink.table.dataformat.GenericRow
-import org.apache.flink.table.dataview.DataViewSpec
-import org.apache.flink.table.functions.AvgAggFunction.{DoubleAvgAggFunction, IntegralAvgAggFunction}
 import org.apache.flink.table.generated.AggsHandleFunction
-import org.apache.flink.table.plan.util.{AggregateInfo, AggregateInfoList}
-import org.apache.calcite.rel.core.AggregateCall
-import org.apache.calcite.tools.FrameworkConfig
-import org.junit.{Assert, Test}
-import org.powermock.api.mockito.PowerMockito.{mock, when}
-import java.lang
-
-import org.apache.flink.table.runtime.context.ExecutionContext
-
-class AggsHandlerCodeGeneratorTest {
-
-  private val typeFactory: FlinkTypeFactory = new FlinkTypeFactory(new FlinkTypeSystem())
-  private val env = new LocalStreamEnvironment
-  private val conf = new TableConfig
-  private val tEnv = new StreamTableEnvironment(env, conf)
-  private val frameworkConfig: FrameworkConfig = tEnv.getFrameworkConfig
-  private val inputNames = Array("f0", "f1", "f2", "f3")
-  private val inputTypes = Array(
-    InternalTypes.STRING,
-    InternalTypes.LONG, InternalTypes.DOUBLE, InternalTypes.LONG)
-  private val relBuilder = FlinkRelBuilder.create(frameworkConfig).values(
-    typeFactory.buildLogicalRowType(inputNames, inputTypes))
-  private val aggInfo1 = {
-    val aggInfo = mock(classOf[AggregateInfo])
-    val call = mock(classOf[AggregateCall])
-    when(aggInfo, "agg").thenReturn(call)
-    when(call, "getName").thenReturn("avg1")
-    when(aggInfo, "function").thenReturn(new IntegralAvgAggFunction)
-    when(aggInfo, "externalAccTypes").thenReturn(Array(Types.LONG, Types.LONG))
-    when(aggInfo, "argIndexes").thenReturn(Array(1))
-    when(aggInfo, "aggIndex").thenReturn(0)
-    aggInfo
-  }
 
-  private val aggInfo2 = {
-    val aggInfo = mock(classOf[AggregateInfo])
-    val call = mock(classOf[AggregateCall])
-    when(aggInfo, "agg").thenReturn(call)
-    when(call, "getName").thenReturn("avg2")
-    when(aggInfo, "function").thenReturn(new DoubleAvgAggFunction)
-    when(aggInfo, "externalAccTypes").thenReturn(Array(Types.DOUBLE, Types.LONG))
-    when(aggInfo, "argIndexes").thenReturn(Array(2))
-    when(aggInfo, "aggIndex").thenReturn(1)
-    aggInfo
-  }
+import org.junit.{Assert, Test}
 
-  private val imperativeAggFunc = new TestLongAvgFunc
-  private val aggInfo3 = {
-    val aggInfo = mock(classOf[AggregateInfo])
-    val call = mock(classOf[AggregateCall])
-    when(aggInfo, "agg").thenReturn(call)
-    when(call, "getName").thenReturn("avg3")
-    when(aggInfo, "function").thenReturn(imperativeAggFunc)
-    when(aggInfo, "externalAccTypes").thenReturn(Array(imperativeAggFunc.getAccumulatorType))
-    when(aggInfo, "externalResultType").thenReturn(Types.DOUBLE)
-    when(aggInfo, "viewSpecs").thenReturn(Array[DataViewSpec]())
-    when(aggInfo, "argIndexes").thenReturn(Array(3))
-    when(aggInfo, "aggIndex").thenReturn(2)
-    aggInfo
-  }
+import java.lang
 
-  private val aggInfoList = AggregateInfoList(
-    Array(aggInfo1, aggInfo2, aggInfo3), None, count1AggInserted = false, Array())
-  private val ctx = new CodeGeneratorContext(conf)
-  private val classLoader = Thread.currentThread().getContextClassLoader
-  private val context = mock(classOf[ExecutionContext])
-  when(context, "getRuntimeContext").thenReturn(mock(classOf[RuntimeContext]))
+class AggsHandlerCodeGeneratorTest extends AggTestBase {
 
   @Test
   def testAvg(): Unit = {
@@ -120,7 +50,7 @@ class AggsHandlerCodeGeneratorTest {
     handler.accumulate(GenericRow.of("f0", jl(7L), jd(7.4D), jl(4L)))
     handler.retract(GenericRow.of("f0", jl(9L), jd(5.5D), jl(5L)))
     val ret = handler.getValue
-    Assert.assertEquals(4.0, ret.getDouble(0), 0)
+    Assert.assertEquals(4.5, ret.getDouble(0), 0)
     Assert.assertEquals(6.75, ret.getDouble(1), 0)
     Assert.assertEquals(2.0, ret.getDouble(2), 0)
   }
@@ -134,9 +64,9 @@ class AggsHandlerCodeGeneratorTest {
     handler.merge(GenericRow.of("f0", jl(43L), jl(1L), jd(4D), jl(1L), jt(43L, 1L)))
     val ret = handler.getValue
     // TODO return 26.6 instead of 26.0 after divide return double instead of long
-    Assert.assertEquals(26.0, ret.getDouble(0), 0)
+    Assert.assertEquals(26.6, ret.getDouble(0), 0)
     Assert.assertEquals(2.6, ret.getDouble(1), 0)
-    Assert.assertEquals(26.0, ret.getDouble(2), 0)
+    Assert.assertEquals(26.6, ret.getDouble(2), 0)
   }
 
   private def jl(l: Long): lang.Long = {
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/batch/AggWithoutKeysTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/batch/AggWithoutKeysTest.scala
new file mode 100644
index 0000000..2069af9
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/batch/AggWithoutKeysTest.scala
@@ -0,0 +1,105 @@
+/*
+ * 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.codegen.agg.batch
+
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator
+import org.apache.flink.table.`type`.{InternalType, InternalTypes, RowType}
+import org.apache.flink.table.`type`.TypeConverters.createInternalTypeFromTypeInfo
+import org.apache.flink.table.dataformat.BaseRow
+import org.apache.flink.table.runtime.OneInputOperatorWrapper
+
+import org.junit.Test
+
+/**
+  * Test for [[AggWithoutKeysCodeGenerator]].
+  */
+class AggWithoutKeysTest extends BatchAggTestBase {
+
+  val localOutputType = new RowType(
+    Array[InternalType](
+      InternalTypes.LONG, InternalTypes.LONG,
+      InternalTypes.DOUBLE, InternalTypes.LONG,
+      createInternalTypeFromTypeInfo(imperativeAggFunc.getAccumulatorType)),
+    Array(
+      "agg1Buffer1", "agg1Buffer2",
+      "agg2Buffer1", "agg2Buffer2",
+      "agg3Buffer"))
+
+  override val globalOutputType = new RowType(
+    Array[InternalType](
+      InternalTypes.DOUBLE,
+      InternalTypes.DOUBLE,
+      InternalTypes.DOUBLE),
+    Array(
+      "agg1Output",
+      "agg2Output",
+      "agg3Output"))
+
+  @Test
+  def testLocal(): Unit = {
+    testOperator(
+      getOperatorWithoutKey(isMerge = false, isFinal = false),
+      Array(
+        row("key1", 8L, 8D, 8L, "aux1"),
+        row("key1", 4L, 4D, 4L, "aux1"),
+        row("key1", 2L, 2D, 2L, "aux1"),
+        row("key2", 3L, 3D, 3L, "aux1")
+      ),
+      Array(row(17L, 4L, 17D, 4L, row(17L, 4L))))
+  }
+
+  @Test
+  def testGlobal(): Unit = {
+    testOperator(
+      getOperatorWithoutKey(isMerge = true, isFinal = true),
+      Array(
+        row(8L, 2L, 8D, 2L, row(8L, 2L)),
+        row(4L, 2L, 4D, 2L, row(4L, 2L)),
+        row(6L, 2L, 6D, 2L, row(6L, 2L))
+      ),
+      Array(row(3.0D, 3.0D, 3.0D)))
+  }
+
+  @Test
+  def testComplete(): Unit = {
+    testOperator(
+      getOperatorWithoutKey(isMerge = false, isFinal = true),
+      Array(
+        row("key1", 8L, 8D, 8L, "aux1"),
+        row("key1", 4L, 4D, 4L, "aux1"),
+        row("key1", 4L, 4D, 4L, "aux1"),
+        row("key1", 4L, 4D, 4L, "aux1")
+      ),
+      Array(row(5.0D, 5.0D, 5.0D)))
+  }
+
+  private def getOperatorWithoutKey(isMerge: Boolean, isFinal: Boolean)
+    : (OneInputStreamOperator[BaseRow, BaseRow], RowType, RowType) = {
+    val (iType, oType) = if (isMerge && isFinal) {
+      (localOutputType, globalOutputType)
+    } else if (!isMerge && isFinal) {
+      (inputType, globalOutputType)
+    } else {
+      (inputType, localOutputType)
+    }
+    val genOp = AggWithoutKeysCodeGenerator.genWithoutKeys(
+      ctx, relBuilder, aggInfoList, iType, oType, isMerge, isFinal, "Without")
+    (new OneInputOperatorWrapper[BaseRow, BaseRow](genOp), iType, oType)
+  }
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/batch/BatchAggTestBase.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/batch/BatchAggTestBase.scala
new file mode 100644
index 0000000..fc1570f
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/batch/BatchAggTestBase.scala
@@ -0,0 +1,103 @@
+/*
+ * 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.codegen.agg.batch
+
+import org.apache.flink.runtime.execution.Environment
+import org.apache.flink.runtime.jobgraph.OperatorID
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator
+import org.apache.flink.streaming.runtime.streamrecord.StreamRecord
+import org.apache.flink.streaming.runtime.tasks.{OneInputStreamTask, OneInputStreamTaskTestHarness, OperatorChain}
+import org.apache.flink.table.`type`.{InternalType, InternalTypes, RowType}
+import org.apache.flink.table.codegen.agg.AggTestBase
+import org.apache.flink.table.dataformat.{BaseRow, BinaryString, GenericRow}
+import org.apache.flink.table.runtime.OneInputOperatorWrapper
+import org.apache.flink.table.util.BaseRowTestUtil
+
+import org.junit.Assert
+
+import java.util
+import java.util.function
+
+import scala.collection.JavaConverters._
+
+/**
+  * Base agg test.
+  */
+abstract class BatchAggTestBase extends AggTestBase {
+
+  val globalOutputType = new RowType(
+    Array[InternalType](
+      InternalTypes.STRING, InternalTypes.STRING,
+      InternalTypes.DOUBLE,
+      InternalTypes.DOUBLE,
+      InternalTypes.DOUBLE),
+    Array(
+      "f0", "f4",
+      "agg1Output",
+      "agg2Output",
+      "agg3Output"))
+
+  def row(args: Any*): GenericRow = {
+    GenericRow.of(args.map {
+      case str: String => BinaryString.fromString(str)
+      case l: Long => Long.box(l)
+      case d: Double => Double.box(d)
+      case o: AnyRef => o
+    }.toArray[AnyRef]: _*)
+  }
+
+  def testOperator(
+      args: (OneInputStreamOperator[BaseRow, BaseRow], RowType, RowType),
+      input: Array[BaseRow], expectedOutput: Array[GenericRow]): Unit = {
+    val testHarness = new OneInputStreamTaskTestHarness[BaseRow, BaseRow](
+      new function.Function[Environment, OneInputStreamTask[BaseRow, BaseRow]] {
+        override def apply(t: Environment) = new OneInputStreamTask(t)
+      }, 1, 1, args._2.toTypeInfo, args._3.toTypeInfo)
+    testHarness.memorySize = 32 * 100 * 1024
+
+    testHarness.setupOutputForSingletonOperatorChain()
+    val streamConfig = testHarness.getStreamConfig
+    streamConfig.setStreamOperator(args._1)
+    streamConfig.setOperatorID(new OperatorID)
+
+    testHarness.invoke()
+    testHarness.waitForTaskRunning()
+
+    for (row <- input) {
+      testHarness.processElement(new StreamRecord[BaseRow](row, 0L))
+    }
+
+    testHarness.waitForInputProcessing()
+
+    val op = testHarness.getTask.getStreamStatusMaintainer.asInstanceOf[OperatorChain[_, _]]
+        .getHeadOperator.asInstanceOf[OneInputOperatorWrapper[_, _]].getOperator
+    op.getClass.getMethod("endInput").invoke(op)
+
+    testHarness.endInput()
+    testHarness.waitForTaskCompletion()
+
+    val outputs = new util.ArrayList[GenericRow]()
+    val outQueue = testHarness.getOutput
+    while (!outQueue.isEmpty) {
+      outputs.add(BaseRowTestUtil.toGenericRowDeeply(
+        outQueue.poll().asInstanceOf[StreamRecord[BaseRow]].getValue, args._3.getFieldTypes))
+    }
+    Assert.assertArrayEquals(expectedOutput.toArray[AnyRef], outputs.asScala.toArray[AnyRef])
+  }
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/batch/HashAggCodeGeneratorTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/batch/HashAggCodeGeneratorTest.scala
new file mode 100644
index 0000000..da0122a
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/batch/HashAggCodeGeneratorTest.scala
@@ -0,0 +1,132 @@
+/*
+ * 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.codegen.agg.batch
+
+import org.apache.flink.api.common.typeinfo.Types
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator
+import org.apache.flink.table.`type`.{InternalType, InternalTypes, RowType}
+import org.apache.flink.table.dataformat.BaseRow
+import org.apache.flink.table.functions.AvgAggFunction.IntegralAvgAggFunction
+import org.apache.flink.table.plan.util.{AggregateInfo, AggregateInfoList}
+import org.apache.flink.table.runtime.OneInputOperatorWrapper
+
+import org.apache.calcite.rel.core.AggregateCall
+import org.junit.Test
+import org.powermock.api.mockito.PowerMockito.{mock, when}
+
+/**
+  * Test for [[HashAggCodeGenerator]].
+  */
+class HashAggCodeGeneratorTest extends BatchAggTestBase {
+
+  val localOutputType = new RowType(
+    Array[InternalType](
+      InternalTypes.STRING, InternalTypes.STRING,
+      InternalTypes.LONG, InternalTypes.LONG,
+      InternalTypes.DOUBLE, InternalTypes.LONG,
+      InternalTypes.LONG, InternalTypes.LONG),
+    Array(
+      "f0", "f4",
+      "agg1Buffer1", "agg1Buffer2",
+      "agg2Buffer1", "agg2Buffer2",
+      "agg3Buffer1", "agg3Buffer2"))
+
+  // override imperativeAggFunc, hash agg only handle DeclarativeAggregateFunction
+  override val aggInfo3: AggregateInfo = {
+    val aggInfo = mock(classOf[AggregateInfo])
+    val call = mock(classOf[AggregateCall])
+    when(aggInfo, "agg").thenReturn(call)
+    when(call, "getName").thenReturn("avg3")
+    when(aggInfo, "function").thenReturn(new IntegralAvgAggFunction)
+    when(aggInfo, "externalAccTypes").thenReturn(Array(Types.LONG, Types.LONG))
+    when(aggInfo, "argIndexes").thenReturn(Array(3))
+    when(aggInfo, "aggIndex").thenReturn(2)
+    aggInfo
+  }
+
+  override val aggInfoList = AggregateInfoList(
+    Array(aggInfo1, aggInfo2, aggInfo3), None, count1AggInserted = false, Array())
+
+  @Test
+  def testLocal(): Unit = {
+    testOperator(
+      getOperatorWithKey(isMerge = false, isFinal = false),
+      Array(
+        row("key1", 8L, 8D, 8L, "aux1"),
+        row("key1", 4L, 4D, 4L, "aux1"),
+        row("key1", 2L, 2D, 2L, "aux1"),
+        row("key2", 3L, 3D, 3L, "aux2")
+      ),
+      Array(
+        row("key1", "aux1", 14L, 3L, 14D, 3L, 14L, 3L),
+        row("key2", "aux2", 3L, 1L, 3D, 1L, 3L, 1L))
+    )
+  }
+
+  @Test
+  def testGlobal(): Unit = {
+    testOperator(
+      getOperatorWithKey(isMerge = true, isFinal = true),
+      Array(
+        row("key1", "aux1", 8L, 2L, 8D, 2L, 8L, 2L),
+        row("key1", "aux1", 4L, 2L, 4D, 2L, 4L, 2L),
+        row("key1", "aux1", 6L, 2L, 6D, 2L, 6L, 2L),
+        row("key2", "aux2", 8L, 2L, 8D, 2L, 8L, 2L)
+      ),
+      Array(
+        row("key1", "aux1", 3.0D, 3.0D, 3.0D),
+        row("key2", "aux2", 4.0D, 4.0D, 4.0D))
+    )
+  }
+
+  @Test
+  def testComplete(): Unit = {
+    testOperator(
+      getOperatorWithKey(isMerge = false, isFinal = true),
+      Array(
+        row("key1", 8L, 8D, 8L, "aux1"),
+        row("key1", 4L, 4D, 4L, "aux1"),
+        row("key1", 4L, 4D, 4L, "aux1"),
+        row("key1", 6L, 6D, 6L, "aux1"),
+        row("key2", 3L, 3D, 3L, "aux2")
+      ),
+      Array(
+        row("key1", "aux1", 5.5D, 5.5D, 5.5D),
+        row("key2", "aux2", 3.0D, 3.0D, 3.0D))
+    )
+  }
+
+  private def getOperatorWithKey(isMerge: Boolean, isFinal: Boolean)
+    : (OneInputStreamOperator[BaseRow, BaseRow], RowType, RowType) = {
+    val (iType, oType) = if (isMerge && isFinal) {
+      (localOutputType, globalOutputType)
+    } else if (!isMerge && isFinal) {
+      (inputType, globalOutputType)
+    } else {
+      (inputType, localOutputType)
+    }
+    val auxGrouping = if (isMerge) Array(1) else Array(4)
+    val generator = new HashAggCodeGenerator(
+      ctx, relBuilder, aggInfoList, iType, oType, Array(0), auxGrouping, isMerge, isFinal)
+    val genOp = generator.genWithKeys(100 * 32 * 1024, 0)
+    (new OneInputOperatorWrapper[BaseRow, BaseRow](genOp), iType, oType)
+  }
+
+
+}
diff --git a/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/batch/SortAggCodeGeneratorTest.scala b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/batch/SortAggCodeGeneratorTest.scala
new file mode 100644
index 0000000..ecf1d7c
--- /dev/null
+++ b/flink-table/flink-table-planner-blink/src/test/scala/org/apache/flink/table/codegen/agg/batch/SortAggCodeGeneratorTest.scala
@@ -0,0 +1,121 @@
+/*
+ * 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.codegen.agg.batch
+
+import org.apache.flink.streaming.api.operators.OneInputStreamOperator
+import org.apache.flink.table.`type`.TypeConverters.createInternalTypeFromTypeInfo
+import org.apache.flink.table.`type`.{InternalType, InternalTypes, RowType}
+import org.apache.flink.table.dataformat.BaseRow
+import org.apache.flink.table.runtime.OneInputOperatorWrapper
+
+import org.junit.Test
+
+/**
+  * Test for [[SortAggCodeGenerator]].
+  */
+class SortAggCodeGeneratorTest extends BatchAggTestBase {
+
+  val localOutputType = new RowType(
+    Array[InternalType](
+      InternalTypes.STRING, InternalTypes.STRING,
+      InternalTypes.LONG, InternalTypes.LONG,
+      InternalTypes.DOUBLE, InternalTypes.LONG,
+      createInternalTypeFromTypeInfo(imperativeAggFunc.getAccumulatorType)),
+    Array(
+      "f0", "f4",
+      "agg1Buffer1", "agg1Buffer2",
+      "agg2Buffer1", "agg2Buffer2",
+      "agg3Buffer"))
+
+  @Test
+  def testLocal(): Unit = {
+    testOperator(
+      getOperatorWithKey(isMerge = false, isFinal = false),
+      Array(
+        row("key1", 8L, 8D, 8L, "aux1"),
+        row("key1", 4L, 4D, 4L, "aux1"),
+        row("key1", 2L, 2D, 2L, "aux1"),
+        row("key2", 3L, 3D, 3L, "aux2")
+      ),
+      Array(
+        row("key1", "aux1", 14L, 3L, 14D, 3L, row(14L, 3L)),
+        row("key2", "aux2", 3L, 1L, 3D, 1L, row(3L, 1L)))
+    )
+  }
+
+  @Test
+  def testGlobal(): Unit = {
+    testOperator(
+      getOperatorWithKey(isMerge = true, isFinal = true),
+      Array(
+        row("key1", "aux1", 8L, 2L, 8D, 2L, row(8L, 2L)),
+        row("key1", "aux1", 4L, 2L, 4D, 2L, row(4L, 2L)),
+        row("key1", "aux1", 6L, 2L, 6D, 2L, row(6L, 2L)),
+        row("key2", "aux2", 8L, 2L, 8D, 2L, row(8L, 2L))
+      ),
+      Array(
+        row("key1", "aux1", 3.0D, 3.0D, 3.0D),
+        row("key2", "aux2", 4.0D, 4.0D, 4.0D))
+    )
+  }
+
+  @Test
+  def testComplete(): Unit = {
+    testOperator(
+      getOperatorWithKey(isMerge = false, isFinal = true),
+      Array(
+        row("key1", 8L, 8D, 8L, "aux1"),
+        row("key1", 4L, 4D, 4L, "aux1"),
+        row("key1", 4L, 4D, 4L, "aux1"),
+        row("key1", 6L, 6D, 6L, "aux1"),
+        row("key2", 3L, 3D, 3L, "aux2")
+      ),
+      Array(
+        row("key1", "aux1", 5.5D, 5.5D, 5.5D),
+        row("key2", "aux2", 3.0D, 3.0D, 3.0D))
+    )
+  }
+
+  private def getOperatorWithKey(isMerge: Boolean, isFinal: Boolean)
+    : (OneInputStreamOperator[BaseRow, BaseRow], RowType, RowType) = {
+    val localOutputType = new RowType(
+      Array[InternalType](
+        InternalTypes.STRING, InternalTypes.STRING,
+        InternalTypes.LONG, InternalTypes.LONG,
+        InternalTypes.DOUBLE, InternalTypes.LONG,
+        createInternalTypeFromTypeInfo(imperativeAggFunc.getAccumulatorType)),
+      Array(
+        "f0", "f4",
+        "agg1Buffer1", "agg1Buffer2",
+        "agg2Buffer1", "agg2Buffer2",
+        "agg3Buffer"))
+
+    val (iType, oType) = if (isMerge && isFinal) {
+      (localOutputType, globalOutputType)
+    } else if (!isMerge && isFinal) {
+      (inputType, globalOutputType)
+    } else {
+      (inputType, localOutputType)
+    }
+    val auxGrouping = if (isMerge) Array(1) else Array(4)
+    val genOp = SortAggCodeGenerator.genWithKeys(
+      ctx, relBuilder, aggInfoList, iType, oType, Array(0), auxGrouping, isMerge, isFinal)
+    (new OneInputOperatorWrapper[BaseRow, BaseRow](genOp), iType, oType)
+  }
+}
diff --git a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/OneInputOperatorWrapper.java b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/OneInputOperatorWrapper.java
index cda6f68..6d02b62 100644
--- a/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/OneInputOperatorWrapper.java
+++ b/flink-table/flink-table-runtime-blink/src/main/java/org/apache/flink/table/runtime/OneInputOperatorWrapper.java
@@ -17,6 +17,7 @@
 
 package org.apache.flink.table.runtime;
 
+import org.apache.flink.annotation.VisibleForTesting;
 import org.apache.flink.metrics.MetricGroup;
 import org.apache.flink.runtime.checkpoint.CheckpointOptions;
 import org.apache.flink.runtime.jobgraph.OperatorID;
@@ -54,6 +55,11 @@ public class OneInputOperatorWrapper<IN, OUT>
 		operator.setup(containingTask, config, output);
 	}
 
+	@VisibleForTesting
+	public OneInputStreamOperator<IN, OUT> getOperator() {
+		return operator;
+	}
+
 	@Override
 	public void open() throws Exception {
 		operator.open();