@@ -679,6 +679,9 @@ public RelNode visitReverse(
679679
680680 @ Override
681681 public RelNode visitBin (Bin node , CalcitePlanContext context ) {
682+ // Mark that this query uses bin operations (for AVG rounding in aggregations)
683+ context .setHasBinOperations (true );
684+
682685 visitChildren (node , context );
683686
684687 RexNode fieldExpr = rexVisitor .analyze (node .getField (), context );
@@ -1264,9 +1267,17 @@ public RelNode visitAggregation(Aggregation node, CalcitePlanContext context) {
12641267 numOfOutputFields - aggregationAttributes .getRight ().size (),
12651268 numOfOutputFields - aggregationAttributes .getRight ().size () + numOfUserAggregations );
12661269
1267- // Check if we have any bin columns (for AVG rounding)
1270+ // Check if we have any bin operations (for AVG rounding)
1271+ // First check the flag set by visitBin
1272+ boolean hasBinColumns = context .isHasBinOperations ();
1273+
1274+ // Get all field names (needed later for schema reordering)
12681275 List <String > allFieldNames = context .relBuilder .peek ().getRowType ().getFieldNames ();
1269- boolean hasBinColumns = allFieldNames .stream ().anyMatch (name -> name .endsWith ("_bin" ));
1276+
1277+ // Also check if we have columns ending with _bin suffix (multi-field bin aggregations)
1278+ if (!hasBinColumns ) {
1279+ hasBinColumns = allFieldNames .stream ().anyMatch (name -> name .endsWith ("_bin" ));
1280+ }
12701281
12711282 // Wrap AVG aggregations with ROUND to fix floating point precision (only when bins are present)
12721283 for (int i = 0 ; i < userAggRexList .size (); i ++) {
0 commit comments