xiedeyantu commented on code in PR #20940:
URL: https://github.com/apache/datafusion/pull/20940#discussion_r2969380745


##########
datafusion/optimizer/src/multi_distinct_to_cross_join.rs:
##########
@@ -0,0 +1,229 @@
+// 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.
+
+//! [`MultiDistinctToCrossJoin`] splits multiple distinct aggregates on
+//! different columns into separate aggregates joined by a cross join,
+//! improving memory locality by executing each distinct aggregate 
sequentially.
+
+use std::sync::Arc;
+
+use crate::optimizer::ApplyOrder;
+use crate::{OptimizerConfig, OptimizerRule};
+
+use datafusion_common::tree_node::Transformed;
+use datafusion_common::{HashSet, Result};
+use datafusion_expr::expr::AggregateFunctionParams;
+use datafusion_expr::expr_fn::ident;
+use datafusion_expr::{
+    Expr, LogicalPlanBuilder,
+    expr::AggregateFunction,
+    logical_plan::{Aggregate, LogicalPlan},
+};
+
+/// Optimizer rule that rewrites queries with multiple distinct aggregates on
+/// different columns (without GROUP BY) into a cross join of individual
+/// aggregates. Each aggregate runs sequentially to completion, improving
+/// memory locality since only one hash table is live at a time.
+///
+/// ```text
+/// Before:
+///   SELECT COUNT(DISTINCT a), COUNT(DISTINCT b) FROM t
+///
+/// After:
+///   SELECT count(DISTINCT a), count(DISTINCT b)
+///   FROM (SELECT COUNT(DISTINCT a) FROM t)
+///   CROSS JOIN (SELECT COUNT(DISTINCT b) FROM t)
+/// ```

Review Comment:
   Are you trying to express rewriting it like this?
   ```
   SELECT s.cnt_a, t.cnt_b
   FROM (SELECT COUNT(DISTINCT a) AS cnt_a FROM t) s
   CROSS JOIN (SELECT COUNT(DISTINCT b) AS cnt_b FROM t) t
   ```



-- 
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]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to