xuzifu666 commented on code in PR #4961:
URL: https://github.com/apache/calcite/pull/4961#discussion_r3292218453


##########
core/src/main/java/org/apache/calcite/rel/rules/AggregateReduceFunctionsOnGroupKeysRule.java:
##########
@@ -147,12 +153,118 @@ protected AggregateReduceFunctionsOnGroupKeysRule(Config 
config) {
     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);
+    final List<Integer> argList = call.getArgList();
+    if (argList.size() != 1) {
+      return null;
+    }
+    final int arg = argList.get(0);
+
+    // Case 1: argument directly references a group-by key
+    if (aggregate.getGroupSet().get(arg)) {
+      final int groupIndex = aggregate.getGroupSet().asList().indexOf(arg);
+      RexNode ref = RexInputRef.of(groupIndex, 
aggregate.getRowType().getFieldList());
+      if (!ref.getType().equals(call.getType())) {

Review Comment:
   Thank you for pointing out the case. I've added a new 
test:`testAggregateFunctionOfGroupByKeysWithCast` to verify that when a CAST is 
inserted due to type mismatch between the GROUP BY key and the aggregate 
result, the optimization correctly preserves the CAST operation.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to