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

xuzifu666 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/calcite.git


The following commit(s) were added to refs/heads/main by this push:
     new 3505dba4cd [CALCITE-7484] Add a rule to eliminate redundant aggregates 
functions over GROUP BY keys
3505dba4cd is described below

commit 3505dba4cd8fcf41676110dbaa82be8b5b9d17d5
Author: Yu Xu <[email protected]>
AuthorDate: Tue Apr 21 21:11:20 2026 +0800

    [CALCITE-7484] Add a rule to eliminate redundant aggregates functions over 
GROUP BY keys
---
 .../AggregateReduceFunctionsOnGroupKeysRule.java   | 178 +++++++++++++++++++++
 .../org/apache/calcite/rel/rules/CoreRules.java    |   6 +
 ...ggregateReduceFunctionsOnGroupKeysRuleTest.java |  67 ++++++++
 ...AggregateReduceFunctionsOnGroupKeysRuleTest.xml |  80 +++++++++
 4 files changed, 331 insertions(+)

diff --git 
a/core/src/main/java/org/apache/calcite/rel/rules/AggregateReduceFunctionsOnGroupKeysRule.java
 
b/core/src/main/java/org/apache/calcite/rel/rules/AggregateReduceFunctionsOnGroupKeysRule.java
new file mode 100644
index 0000000000..10d30d620e
--- /dev/null
+++ 
b/core/src/main/java/org/apache/calcite/rel/rules/AggregateReduceFunctionsOnGroupKeysRule.java
@@ -0,0 +1,178 @@
+/*
+ * 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.calcite.rel.rules;
+
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.plan.RelRule;
+import org.apache.calcite.rel.RelCollations;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Aggregate;
+import org.apache.calcite.rel.core.AggregateCall;
+import org.apache.calcite.rel.core.RelFactories;
+import org.apache.calcite.rel.logical.LogicalAggregate;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.tools.RelBuilder;
+
+import org.checkerframework.checker.nullness.qual.Nullable;
+import org.immutables.value.Value;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Planner rule that eliminates aggregate functions of GROUP BY keys.
+ *
+ * <p>For example,
+ * {@code SELECT sal, max(sal) FROM emp GROUP BY sal}
+ * can be simplified to
+ * {@code SELECT sal, sal FROM emp GROUP BY sal}.
+ *
+ * <p>Currently supports the following aggregate functions when their
+ * arguments exist in the aggregate's group set:
+ * <ul>
+ *   <li>{@code MAX}</li>
+ *   <li>{@code MIN}</li>
+ *   <li>{@code AVG}</li>
+ *   <li>{@code ANY_VALUE}</li>
+ * </ul>
+ *
+ * @see CoreRules#AGGREGATE_REDUCE_FUNCTIONS_ON_GROUP_KEYS
+ */
[email protected]
+public class AggregateReduceFunctionsOnGroupKeysRule
+    extends RelRule<AggregateReduceFunctionsOnGroupKeysRule.Config>
+    implements TransformationRule {
+
+  /** Creates an AggregateReduceFunctionsOnGroupKeysRule. */
+  protected AggregateReduceFunctionsOnGroupKeysRule(Config config) {
+    super(config);
+  }
+
+  @Override public void onMatch(RelOptRuleCall call) {
+    final Aggregate aggregate = call.rel(0);
+    final List<AggregateCall> oldCalls = aggregate.getAggCallList();
+    final int groupCount = aggregate.getGroupCount();
+    final RexBuilder rexBuilder = aggregate.getCluster().getRexBuilder();
+    final RelBuilder relBuilder = call.builder();
+
+    final List<AggregateCall> newCalls = new ArrayList<>();
+    final List<RexNode> projects = new ArrayList<>();
+
+    // Pass through group keys.
+    for (int i = 0; i < groupCount; i++) {
+      projects.add(rexBuilder.makeInputRef(aggregate, i));
+    }
+
+    boolean changed = false;
+    int newCallOrdinal = 0;
+    for (AggregateCall oldCall : oldCalls) {
+      final @Nullable RexNode reduced = reduce(aggregate, oldCall, rexBuilder);
+      if (reduced != null) {
+        projects.add(reduced);
+        changed = true;
+      } else {
+        newCalls.add(oldCall);
+        projects.add(
+            rexBuilder.makeInputRef(
+                oldCall.getType(), groupCount + newCallOrdinal));
+        newCallOrdinal++;
+      }
+    }
+
+    if (!changed) {
+      return;
+    }
+
+    final RelNode newAggregate =
+        aggregate.copy(
+            aggregate.getTraitSet(),
+            aggregate.getInput(),
+            aggregate.getGroupSet(),
+            aggregate.getGroupSets(),
+            newCalls);
+    relBuilder.push(newAggregate);
+    relBuilder.project(projects);
+    call.transformTo(relBuilder.build());
+  }
+
+  /**
+   * Tries to reduce an aggregate call to a reference to a group-by key.
+   *
+   * @return the reduced expression, or null if cannot reduce
+   */
+  private static @Nullable RexNode reduce(
+      Aggregate aggregate,
+      AggregateCall call,
+      RexBuilder rexBuilder) {
+    if (!Aggregate.isSimple(aggregate)) {
+      return null;
+    }
+    if (call.hasFilter()
+        || call.distinctKeys != null
+        || call.collation != RelCollations.EMPTY) {
+      return null;
+    }
+    final List<Integer> argList = call.getArgList();
+    if (argList.size() != 1) {
+      return null;
+    }
+    final int arg = argList.get(0);
+    if (!aggregate.getGroupSet().get(arg)) {
+      return null;
+    }
+    final SqlKind kind = call.getAggregation().getKind();
+    switch (kind) {
+    case AVG:
+    case MAX:
+    case MIN:
+    case ANY_VALUE:
+      break;
+    default:
+      return null;
+    }
+    final int groupIndex = aggregate.getGroupSet().asList().indexOf(arg);
+    RexNode ref = RexInputRef.of(groupIndex, 
aggregate.getRowType().getFieldList());
+    if (!ref.getType().equals(call.getType())) {
+      ref = rexBuilder.makeCast(call.getParserPosition(), call.getType(), ref);
+    }
+    return ref;
+  }
+
+  /** Rule configuration. */
+  @Value.Immutable
+  public interface Config extends RelRule.Config {
+    Config DEFAULT = 
ImmutableAggregateReduceFunctionsOnGroupKeysRule.Config.of()
+        .withRelBuilderFactory(RelFactories.LOGICAL_BUILDER)
+        .withOperandFor(LogicalAggregate.class);
+
+    @Override default AggregateReduceFunctionsOnGroupKeysRule toRule() {
+      return new AggregateReduceFunctionsOnGroupKeysRule(this);
+    }
+
+    /** Defines an operand tree for the given class. */
+    default Config withOperandFor(Class<? extends Aggregate> aggregateClass) {
+      return withOperandSupplier(b ->
+          b.operand(aggregateClass)
+              .predicate(Aggregate::isSimple)
+              .anyInputs())
+          .as(Config.class);
+    }
+  }
+}
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/CoreRules.java 
b/core/src/main/java/org/apache/calcite/rel/rules/CoreRules.java
index d7068dcc7c..873d04016f 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/CoreRules.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/CoreRules.java
@@ -99,6 +99,12 @@ private CoreRules() {}
   public static final AggregateReduceFunctionsRule AGGREGATE_REDUCE_FUNCTIONS =
       AggregateReduceFunctionsRule.Config.DEFAULT.toRule();
 
+  /** Rule that eliminates aggregate functions of GROUP BY keys
+   * in an {@link Aggregate}. */
+  public static final AggregateReduceFunctionsOnGroupKeysRule
+      AGGREGATE_REDUCE_FUNCTIONS_ON_GROUP_KEYS =
+      AggregateReduceFunctionsOnGroupKeysRule.Config.DEFAULT.toRule();
+
   /** Rule that matches an {@link Aggregate} on an {@link Aggregate},
    * and merges into a single Aggregate if the top aggregate's group key is a
    * subset of the lower aggregate's group key, and the aggregates are
diff --git 
a/core/src/test/java/org/apache/calcite/test/AggregateReduceFunctionsOnGroupKeysRuleTest.java
 
b/core/src/test/java/org/apache/calcite/test/AggregateReduceFunctionsOnGroupKeysRuleTest.java
new file mode 100644
index 0000000000..739ce1cb0b
--- /dev/null
+++ 
b/core/src/test/java/org/apache/calcite/test/AggregateReduceFunctionsOnGroupKeysRuleTest.java
@@ -0,0 +1,67 @@
+/*
+ * 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.calcite.test;
+
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Test;
+
+import static 
org.apache.calcite.rel.rules.CoreRules.AGGREGATE_REDUCE_FUNCTIONS_ON_GROUP_KEYS;
+
+/**
+ * Unit tests for {@link 
org.apache.calcite.rel.rules.AggregateReduceFunctionsOnGroupKeysRule}.
+ *
+ * <p>Relevant tickets:
+ * <ul>
+ * <li><a href="https://issues.apache.org/jira/browse/CALCITE-7484";>
+ * [CALCITE-7484] Add a rule to eliminate redundant aggregates functions over 
GROUP BY keys
+ * </a></li>
+ * </ul>
+ */
+class AggregateReduceFunctionsOnGroupKeysRuleTest {
+
+  private static RelOptFixture fixture() {
+    return RelOptFixture.DEFAULT.withDiffRepos(
+        
DiffRepository.lookup(AggregateReduceFunctionsOnGroupKeysRuleTest.class));
+  }
+
+  private static RelOptFixture sql(String sql) {
+    return fixture().sql(sql);
+  }
+
+  @Test void testAggregateFunctionOfGroupByKeys() {
+    String sql = "select sal, max(sal) as sal_max, min(sal) as sal_min,\n"
+        + "avg(sal) sal_avg, any_value(sal) as sal_val\n"
+        + "from emp group by sal, deptno";
+    sql(sql).withRule(AGGREGATE_REDUCE_FUNCTIONS_ON_GROUP_KEYS).check();
+  }
+
+  @Test void testAggregateFunctionOfGroupByKeysPartial() {
+    String sql = "select sal, max(sal) as sal_max, sum(comm) as comm_sum\n"
+        + "from emp group by sal, deptno";
+    sql(sql).withRule(AGGREGATE_REDUCE_FUNCTIONS_ON_GROUP_KEYS).check();
+  }
+
+  @Test void testAggregateFunctionOfGroupByKeysNoChange() {
+    String sql = "select sal, max(comm) as comm_max\n"
+        + "from emp group by sal, deptno";
+    
sql(sql).withRule(AGGREGATE_REDUCE_FUNCTIONS_ON_GROUP_KEYS).checkUnchanged();
+  }
+
+  @AfterAll static void checkActualAndReferenceFiles() {
+    fixture().diffRepos.checkActualAndReferenceFiles();
+  }
+}
diff --git 
a/core/src/test/resources/org/apache/calcite/test/AggregateReduceFunctionsOnGroupKeysRuleTest.xml
 
b/core/src/test/resources/org/apache/calcite/test/AggregateReduceFunctionsOnGroupKeysRuleTest.xml
new file mode 100644
index 0000000000..e7eb9d5a92
--- /dev/null
+++ 
b/core/src/test/resources/org/apache/calcite/test/AggregateReduceFunctionsOnGroupKeysRuleTest.xml
@@ -0,0 +1,80 @@
+<?xml version="1.0" ?>
+<!--
+  ~ 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.
+  -->
+<Root>
+  <TestCase name="testAggregateFunctionOfGroupByKeys">
+    <Resource name="sql">
+      <![CDATA[select sal, max(sal) as sal_max, min(sal) as sal_min,
+avg(sal) sal_avg, any_value(sal) as sal_val
+from emp group by sal, deptno]]>
+    </Resource>
+    <Resource name="planBefore">
+      <![CDATA[
+LogicalProject(SAL=[$0], SAL_MAX=[$2], SAL_MIN=[$3], SAL_AVG=[$4], 
SAL_VAL=[$5])
+  LogicalAggregate(group=[{0, 1}], SAL_MAX=[MAX($0)], SAL_MIN=[MIN($0)], 
SAL_AVG=[AVG($0)], SAL_VAL=[ANY_VALUE($0)])
+    LogicalProject(SAL=[$5], DEPTNO=[$7])
+      LogicalTableScan(table=[[CATALOG, SALES, EMP]])
+]]>
+    </Resource>
+    <Resource name="planAfter">
+      <![CDATA[
+LogicalProject(SAL=[$0], SAL_MAX=[$2], SAL_MIN=[$3], SAL_AVG=[$4], 
SAL_VAL=[$5])
+  LogicalProject(SAL=[$0], DEPTNO=[$1], SAL0=[$0], SAL1=[$0], SAL2=[$0], 
SAL3=[$0])
+    LogicalAggregate(group=[{0, 1}])
+      LogicalProject(SAL=[$5], DEPTNO=[$7])
+        LogicalTableScan(table=[[CATALOG, SALES, EMP]])
+]]>
+    </Resource>
+  </TestCase>
+  <TestCase name="testAggregateFunctionOfGroupByKeysNoChange">
+    <Resource name="sql">
+      <![CDATA[select sal, max(comm) as comm_max
+from emp group by sal, deptno]]>
+    </Resource>
+    <Resource name="planBefore">
+      <![CDATA[
+LogicalProject(SAL=[$0], COMM_MAX=[$2])
+  LogicalAggregate(group=[{0, 1}], COMM_MAX=[MAX($2)])
+    LogicalProject(SAL=[$5], DEPTNO=[$7], COMM=[$6])
+      LogicalTableScan(table=[[CATALOG, SALES, EMP]])
+]]>
+    </Resource>
+  </TestCase>
+  <TestCase name="testAggregateFunctionOfGroupByKeysPartial">
+    <Resource name="sql">
+      <![CDATA[select sal, max(sal) as sal_max, sum(comm) as comm_sum
+from emp group by sal, deptno]]>
+    </Resource>
+    <Resource name="planBefore">
+      <![CDATA[
+LogicalProject(SAL=[$0], SAL_MAX=[$2], COMM_SUM=[$3])
+  LogicalAggregate(group=[{0, 1}], SAL_MAX=[MAX($0)], COMM_SUM=[SUM($2)])
+    LogicalProject(SAL=[$5], DEPTNO=[$7], COMM=[$6])
+      LogicalTableScan(table=[[CATALOG, SALES, EMP]])
+]]>
+    </Resource>
+    <Resource name="planAfter">
+      <![CDATA[
+LogicalProject(SAL=[$0], SAL_MAX=[$2], COMM_SUM=[$3])
+  LogicalProject(SAL=[$0], DEPTNO=[$1], SAL0=[$0], COMM_SUM=[$2])
+    LogicalAggregate(group=[{0, 1}], COMM_SUM=[SUM($2)])
+      LogicalProject(SAL=[$5], DEPTNO=[$7], COMM=[$6])
+        LogicalTableScan(table=[[CATALOG, SALES, EMP]])
+]]>
+    </Resource>
+  </TestCase>
+</Root>

Reply via email to