From 442dc110559e06579df4e578da08bd13d540ec01 Mon Sep 17 00:00:00 2001 From: Qiwei Huang Date: Thu, 18 Jun 2026 22:28:01 +0800 Subject: [PATCH 1/2] Prune implicit FD group keys in SQL aggregates --- datafusion/sql/src/select.rs | 113 ++++++++++++++-- .../sqllogictest/test_files/group_by.slt | 4 +- .../test_files/group_by_fd_prune.slt | 121 ++++++++++++++++++ 3 files changed, 226 insertions(+), 12 deletions(-) create mode 100644 datafusion/sqllogictest/test_files/group_by_fd_prune.slt diff --git a/datafusion/sql/src/select.rs b/datafusion/sql/src/select.rs index b0099b8a1dcc3..31a92a9c1177c 100644 --- a/datafusion/sql/src/select.rs +++ b/datafusion/sql/src/select.rs @@ -32,7 +32,10 @@ use crate::utils::{ use arrow::datatypes::DataType; use datafusion_common::error::DataFusionErrorBuilder; use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion}; -use datafusion_common::{Column, DFSchema, DFSchemaRef, Result, not_impl_err, plan_err}; +use datafusion_common::{ + Column, DFSchema, DFSchemaRef, Result, get_target_functional_dependencies, + not_impl_err, plan_err, +}; use datafusion_common::{RecursionUnnestOption, UnnestOptions}; use datafusion_expr::ExprSchemable; use datafusion_expr::builder::get_struct_unnested_columns; @@ -45,8 +48,8 @@ use datafusion_expr::utils::{ expr_as_column_expr, expr_to_columns, find_aggregate_exprs, find_window_exprs, }; use datafusion_expr::{ - Aggregate, Expr, Filter, GroupingSet, LogicalPlan, LogicalPlanBuilder, - LogicalPlanBuilderOptions, Partitioning, SortExpr, + Aggregate, Expr, Filter, GroupingSet, LogicalPlan, LogicalPlanBuilder, Partitioning, + SortExpr, }; use indexmap::IndexMap; @@ -90,6 +93,89 @@ fn flatten_expr_groups(expr_groups: Vec>) -> Vec { expr_groups.into_iter().flatten().collect() } +fn referenced_columns_outside_aggregates( + expr: &Expr, + accum: &mut HashSet, +) -> Result<()> { + expr.apply(|nested_expr| match nested_expr { + Expr::Column(column) => { + accum.insert(column.clone()); + Ok(TreeNodeRecursion::Continue) + } + Expr::AggregateFunction(_) => Ok(TreeNodeRecursion::Jump), + _ => Ok(TreeNodeRecursion::Continue), + }) + .map(|_| ()) +} + +fn required_aggregate_output_columns( + schema: &DFSchemaRef, + select_exprs: &[Expr], + having_expr_opt: Option<&Expr>, + qualify_expr_opt: Option<&Expr>, + order_by_exprs: &[SortExpr], + on_exprs: &[Expr], +) -> Result> { + let mut columns = HashSet::new(); + + for expr in select_exprs { + referenced_columns_outside_aggregates(expr, &mut columns)?; + } + if let Some(expr) = having_expr_opt { + referenced_columns_outside_aggregates(expr, &mut columns)?; + } + if let Some(expr) = qualify_expr_opt { + referenced_columns_outside_aggregates(expr, &mut columns)?; + } + for sort_expr in order_by_exprs { + referenced_columns_outside_aggregates(&sort_expr.expr, &mut columns)?; + } + for expr in on_exprs { + referenced_columns_outside_aggregates(expr, &mut columns)?; + } + + let mut required_columns = HashSet::new(); + for column in &columns { + if let Ok((qualifier, field)) = schema.qualified_field_from_column(column) { + required_columns.insert( + Expr::Column(Column::from((qualifier, field))) + .schema_name() + .to_string(), + ); + } + } + + Ok(required_columns) +} + +fn add_required_group_by_exprs_from_dependencies( + mut group_expr: Vec, + schema: &DFSchemaRef, + required_output_columns: &HashSet, +) -> Result> { + let mut group_by_field_names = group_expr + .iter() + .map(|expr| expr.schema_name().to_string()) + .collect::>(); + + if let Some(target_indices) = + get_target_functional_dependencies(schema, &group_by_field_names) + { + for idx in target_indices { + let expr = Expr::Column(Column::from(schema.qualified_field(idx))); + let expr_name = expr.schema_name().to_string(); + if required_output_columns.contains(&expr_name) + && !group_by_field_names.contains(&expr_name) + { + group_by_field_names.push(expr_name); + group_expr.push(expr); + } + } + } + + Ok(group_expr) +} + impl SqlToRel<'_, S> { /// Generate a logic plan from an SQL select pub(super) fn select_to_plan( @@ -733,10 +819,7 @@ impl SqlToRel<'_, S> { let agg_expr = agg.aggr_expr.clone(); let (new_input, new_group_by_exprs) = self.try_process_group_by_unnest(agg)?; - let options = LogicalPlanBuilderOptions::new() - .with_add_implicit_group_by_exprs(true); LogicalPlanBuilder::from(new_input) - .with_options(options) .aggregate(new_group_by_exprs, agg_expr)? .build() } @@ -1179,11 +1262,21 @@ impl SqlToRel<'_, S> { aggr_exprs: &[Expr], ) -> Result { // create the aggregate plan - let options = - LogicalPlanBuilderOptions::new().with_add_implicit_group_by_exprs(true); + let required_output_columns = required_aggregate_output_columns( + input.schema(), + select_exprs, + having_expr_opt, + qualify_expr_opt, + order_by_exprs, + on_exprs, + )?; + let group_by_exprs = add_required_group_by_exprs_from_dependencies( + group_by_exprs.to_vec(), + input.schema(), + &required_output_columns, + )?; let plan = LogicalPlanBuilder::from(input.clone()) - .with_options(options) - .aggregate(group_by_exprs.to_vec(), aggr_exprs.to_vec())? + .aggregate(group_by_exprs, aggr_exprs.to_vec())? .build()?; let group_by_exprs = if let LogicalPlan::Aggregate(agg) = &plan { &agg.group_expr diff --git a/datafusion/sqllogictest/test_files/group_by.slt b/datafusion/sqllogictest/test_files/group_by.slt index 8c055c25caeb2..6968156e59b17 100644 --- a/datafusion/sqllogictest/test_files/group_by.slt +++ b/datafusion/sqllogictest/test_files/group_by.slt @@ -3602,7 +3602,7 @@ SELECT column1, COUNT(*) as column2 FROM (VALUES (['a', 'b'], 1), (['c', 'd', 'e # primary key should be aware from which columns it is associated -statement error DataFusion error: Error during planning: Column in SELECT must be in GROUP BY or an aggregate function: While expanding wildcard, column "r\.sn" must appear in the GROUP BY clause or must be part of an aggregate function, currently only "l\.sn, l\.zip_code, l\.country, l\.ts, l\.currency, l\.amount, sum\(l\.amount\)" appears in the SELECT clause satisfies this requirement +statement error DataFusion error: Error during planning: Column in SELECT must be in GROUP BY or an aggregate function: While expanding wildcard, column "r\.sn" must appear in the GROUP BY clause or must be part of an aggregate function, currently only "l\.sn, sum\(l\.amount\)" appears in the SELECT clause satisfies this requirement SELECT l.sn, r.sn, SUM(l.amount), r.amount FROM sales_global_with_pk AS l JOIN sales_global_with_pk AS r @@ -3692,7 +3692,7 @@ ORDER BY r.sn 4 100 2022-01-03T10:00:00 # after join, new window expressions shouldn't be associated with primary keys -statement error DataFusion error: Error during planning: Column in SELECT must be in GROUP BY or an aggregate function: While expanding wildcard, column "rn1" must appear in the GROUP BY clause or must be part of an aggregate function, currently only "r\.sn, r\.ts, r\.amount, sum\(r\.amount\)" appears in the SELECT clause satisfies this requirement +statement error DataFusion error: Error during planning: Column in SELECT must be in GROUP BY or an aggregate function: While expanding wildcard, column "rn1" must appear in the GROUP BY clause or must be part of an aggregate function, currently only "r\.sn, sum\(r\.amount\)" appears in the SELECT clause satisfies this requirement SELECT r.sn, SUM(r.amount), rn1 FROM (SELECT r.ts, r.sn, r.amount, diff --git a/datafusion/sqllogictest/test_files/group_by_fd_prune.slt b/datafusion/sqllogictest/test_files/group_by_fd_prune.slt new file mode 100644 index 0000000000000..16c65b4c559f0 --- /dev/null +++ b/datafusion/sqllogictest/test_files/group_by_fd_prune.slt @@ -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. + +# Functional-dependency targets should only be added to aggregate +# GROUP BY outputs when the SQL query actually needs them after +# aggregation. + +statement ok +CREATE TABLE fd_group_by_pk ( + id INT, + name VARCHAR, + amount FLOAT, + PRIMARY KEY(id) +) AS VALUES + (1, 'a', 10.0), + (2, 'b', 20.0), + (3, 'c', 30.0) + +statement ok +set datafusion.explain.logical_plan_only = true; + +# Unreferenced columns determined by the primary key are not appended +# to the aggregate group keys. +query TT +EXPLAIN SELECT id, SUM(amount) +FROM fd_group_by_pk +GROUP BY id +ORDER BY id +---- +logical_plan +01)Sort: fd_group_by_pk.id ASC NULLS LAST +02)--Aggregate: groupBy=[[fd_group_by_pk.id]], aggr=[[sum(CAST(fd_group_by_pk.amount AS Float64))]] +03)----TableScan: fd_group_by_pk projection=[id, amount] + +# SELECT references to functionally-dependent columns still make +# those columns available after aggregation. +query TT +EXPLAIN SELECT id, name, SUM(amount) +FROM fd_group_by_pk +GROUP BY id +ORDER BY id +---- +logical_plan +01)Sort: fd_group_by_pk.id ASC NULLS LAST +02)--Aggregate: groupBy=[[fd_group_by_pk.id, fd_group_by_pk.name]], aggr=[[sum(CAST(fd_group_by_pk.amount AS Float64))]] +03)----TableScan: fd_group_by_pk projection=[id, name, amount] + +# HAVING references to functionally-dependent columns also keep them +# available for the post-aggregate filter. +query TT +EXPLAIN SELECT id, SUM(amount) +FROM fd_group_by_pk +GROUP BY id +HAVING name IS NOT NULL OR SUM(amount) > 0 +ORDER BY id +---- +logical_plan +01)Sort: fd_group_by_pk.id ASC NULLS LAST +02)--Projection: fd_group_by_pk.id, sum(fd_group_by_pk.amount) +03)----Filter: fd_group_by_pk.name IS NOT NULL OR sum(fd_group_by_pk.amount) > Float64(0) +04)------Aggregate: groupBy=[[fd_group_by_pk.id, fd_group_by_pk.name]], aggr=[[sum(CAST(fd_group_by_pk.amount AS Float64))]] +05)--------TableScan: fd_group_by_pk projection=[id, name, amount] + +# ORDER BY references to functionally-dependent columns keep them +# available as hidden aggregate outputs. +query TT +EXPLAIN SELECT id, SUM(amount) +FROM fd_group_by_pk +GROUP BY id +ORDER BY name +---- +logical_plan +01)Projection: fd_group_by_pk.id, sum(fd_group_by_pk.amount) +02)--Sort: fd_group_by_pk.name ASC NULLS LAST +03)----Projection: fd_group_by_pk.id, sum(fd_group_by_pk.amount), fd_group_by_pk.name +04)------Aggregate: groupBy=[[fd_group_by_pk.id, fd_group_by_pk.name]], aggr=[[sum(CAST(fd_group_by_pk.amount AS Float64))]] +05)--------TableScan: fd_group_by_pk projection=[id, name, amount] + +# DISTINCT ON references to functionally-dependent columns also keep +# them available for the post-aggregate distinct grouping. +query TT +EXPLAIN SELECT DISTINCT ON (name) id, SUM(amount) +FROM fd_group_by_pk +GROUP BY id +ORDER BY name +---- +logical_plan +01)Projection: first_value(fd_group_by_pk.id) ORDER BY [fd_group_by_pk.name ASC NULLS LAST] AS id, first_value(sum(fd_group_by_pk.amount)) ORDER BY [fd_group_by_pk.name ASC NULLS LAST] AS sum(fd_group_by_pk.amount) +02)--Sort: fd_group_by_pk.name ASC NULLS LAST +03)----Aggregate: groupBy=[[fd_group_by_pk.name]], aggr=[[first_value(fd_group_by_pk.id) ORDER BY [fd_group_by_pk.name ASC NULLS LAST], first_value(sum(fd_group_by_pk.amount)) ORDER BY [fd_group_by_pk.name ASC NULLS LAST]]] +04)------Aggregate: groupBy=[[fd_group_by_pk.id, fd_group_by_pk.name]], aggr=[[sum(CAST(fd_group_by_pk.amount AS Float64))]] +05)--------TableScan: fd_group_by_pk projection=[id, name, amount] + +# Ordinal grouping still resolves before dependency pruning. +query TT +EXPLAIN SELECT id, SUM(amount) +FROM fd_group_by_pk +GROUP BY 1 +ORDER BY id +---- +logical_plan +01)Sort: fd_group_by_pk.id ASC NULLS LAST +02)--Aggregate: groupBy=[[fd_group_by_pk.id]], aggr=[[sum(CAST(fd_group_by_pk.amount AS Float64))]] +03)----TableScan: fd_group_by_pk projection=[id, amount] + +statement ok +RESET datafusion.explain.logical_plan_only; From 8f532f050c81c698057598fdd66c28844f72a42d Mon Sep 17 00:00:00 2001 From: Qiwei Huang Date: Sat, 20 Jun 2026 20:10:10 +0800 Subject: [PATCH 2/2] Fix projection functional dependency remapping --- datafusion/expr/src/logical_plan/plan.rs | 45 +++++-- datafusion/sql/src/select.rs | 113 ++-------------- .../sqllogictest/test_files/group_by.slt | 4 +- .../test_files/group_by_fd_prune.slt | 121 ------------------ 4 files changed, 49 insertions(+), 234 deletions(-) delete mode 100644 datafusion/sqllogictest/test_files/group_by_fd_prune.slt diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rs index 9ca6941a61ce6..0858c1ad84081 100644 --- a/datafusion/expr/src/logical_plan/plan.rs +++ b/datafusion/expr/src/logical_plan/plan.rs @@ -4144,6 +4144,8 @@ fn calc_func_dependencies_for_project( exprs: &[Expr], input: &LogicalPlan, ) -> Result { + const COMPUTED_EXPR_INDEX: usize = usize::MAX; + let input_fields = input.schema().field_names(); // Calculate expression indices (if present) in the input schema. let proj_indices = exprs @@ -4161,30 +4163,33 @@ fn calc_func_dependencies_for_project( Ok::<_, DataFusionError>( wildcard_fields .into_iter() - .filter_map(|(qualifier, f)| { + .map(|(qualifier, f)| { let flat_name = qualifier .map(|t| format!("{}.{}", t, f.name())) .unwrap_or_else(|| f.name().clone()); - input_fields.iter().position(|item| *item == flat_name) + input_fields + .iter() + .position(|item| *item == flat_name) + .unwrap_or(COMPUTED_EXPR_INDEX) }) .collect::>(), ) } Expr::Alias(alias) => { let name = format!("{}", alias.expr); - Ok(input_fields + let input_index = input_fields .iter() .position(|item| *item == name) - .map(|i| vec![i]) - .unwrap_or(vec![])) + .unwrap_or(COMPUTED_EXPR_INDEX); + Ok(vec![input_index]) } _ => { let name = format!("{expr}"); - Ok(input_fields + let input_index = input_fields .iter() .position(|item| *item == name) - .map(|i| vec![i]) - .unwrap_or(vec![])) + .unwrap_or(COMPUTED_EXPR_INDEX); + Ok(vec![input_index]) } }) .collect::>>()? @@ -4947,6 +4952,30 @@ mod tests { ]) } + #[test] + fn projection_with_leading_computed_column_preserves_pk() -> Result<()> { + let constraints = + Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]); + let source = Arc::new( + LogicalTableSource::new(Arc::new(employee_schema())) + .with_constraints(constraints), + ); + let plan = LogicalPlanBuilder::scan("employee_csv", source, None)? + .project(vec![ + lit(1i32).alias("__common_expr_1"), + col("id"), + col("first_name"), + col("salary"), + ])? + .build()?; + + let deps = plan.schema().functional_dependencies(); + assert_eq!(deps.len(), 1); + assert_eq!(deps[0].source_indices, vec![1]); + + Ok(()) + } + fn i32_split_point(value: i32) -> SplitPoint { SplitPoint::new(vec![ScalarValue::Int32(Some(value))]) } diff --git a/datafusion/sql/src/select.rs b/datafusion/sql/src/select.rs index 31a92a9c1177c..b0099b8a1dcc3 100644 --- a/datafusion/sql/src/select.rs +++ b/datafusion/sql/src/select.rs @@ -32,10 +32,7 @@ use crate::utils::{ use arrow::datatypes::DataType; use datafusion_common::error::DataFusionErrorBuilder; use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion}; -use datafusion_common::{ - Column, DFSchema, DFSchemaRef, Result, get_target_functional_dependencies, - not_impl_err, plan_err, -}; +use datafusion_common::{Column, DFSchema, DFSchemaRef, Result, not_impl_err, plan_err}; use datafusion_common::{RecursionUnnestOption, UnnestOptions}; use datafusion_expr::ExprSchemable; use datafusion_expr::builder::get_struct_unnested_columns; @@ -48,8 +45,8 @@ use datafusion_expr::utils::{ expr_as_column_expr, expr_to_columns, find_aggregate_exprs, find_window_exprs, }; use datafusion_expr::{ - Aggregate, Expr, Filter, GroupingSet, LogicalPlan, LogicalPlanBuilder, Partitioning, - SortExpr, + Aggregate, Expr, Filter, GroupingSet, LogicalPlan, LogicalPlanBuilder, + LogicalPlanBuilderOptions, Partitioning, SortExpr, }; use indexmap::IndexMap; @@ -93,89 +90,6 @@ fn flatten_expr_groups(expr_groups: Vec>) -> Vec { expr_groups.into_iter().flatten().collect() } -fn referenced_columns_outside_aggregates( - expr: &Expr, - accum: &mut HashSet, -) -> Result<()> { - expr.apply(|nested_expr| match nested_expr { - Expr::Column(column) => { - accum.insert(column.clone()); - Ok(TreeNodeRecursion::Continue) - } - Expr::AggregateFunction(_) => Ok(TreeNodeRecursion::Jump), - _ => Ok(TreeNodeRecursion::Continue), - }) - .map(|_| ()) -} - -fn required_aggregate_output_columns( - schema: &DFSchemaRef, - select_exprs: &[Expr], - having_expr_opt: Option<&Expr>, - qualify_expr_opt: Option<&Expr>, - order_by_exprs: &[SortExpr], - on_exprs: &[Expr], -) -> Result> { - let mut columns = HashSet::new(); - - for expr in select_exprs { - referenced_columns_outside_aggregates(expr, &mut columns)?; - } - if let Some(expr) = having_expr_opt { - referenced_columns_outside_aggregates(expr, &mut columns)?; - } - if let Some(expr) = qualify_expr_opt { - referenced_columns_outside_aggregates(expr, &mut columns)?; - } - for sort_expr in order_by_exprs { - referenced_columns_outside_aggregates(&sort_expr.expr, &mut columns)?; - } - for expr in on_exprs { - referenced_columns_outside_aggregates(expr, &mut columns)?; - } - - let mut required_columns = HashSet::new(); - for column in &columns { - if let Ok((qualifier, field)) = schema.qualified_field_from_column(column) { - required_columns.insert( - Expr::Column(Column::from((qualifier, field))) - .schema_name() - .to_string(), - ); - } - } - - Ok(required_columns) -} - -fn add_required_group_by_exprs_from_dependencies( - mut group_expr: Vec, - schema: &DFSchemaRef, - required_output_columns: &HashSet, -) -> Result> { - let mut group_by_field_names = group_expr - .iter() - .map(|expr| expr.schema_name().to_string()) - .collect::>(); - - if let Some(target_indices) = - get_target_functional_dependencies(schema, &group_by_field_names) - { - for idx in target_indices { - let expr = Expr::Column(Column::from(schema.qualified_field(idx))); - let expr_name = expr.schema_name().to_string(); - if required_output_columns.contains(&expr_name) - && !group_by_field_names.contains(&expr_name) - { - group_by_field_names.push(expr_name); - group_expr.push(expr); - } - } - } - - Ok(group_expr) -} - impl SqlToRel<'_, S> { /// Generate a logic plan from an SQL select pub(super) fn select_to_plan( @@ -819,7 +733,10 @@ impl SqlToRel<'_, S> { let agg_expr = agg.aggr_expr.clone(); let (new_input, new_group_by_exprs) = self.try_process_group_by_unnest(agg)?; + let options = LogicalPlanBuilderOptions::new() + .with_add_implicit_group_by_exprs(true); LogicalPlanBuilder::from(new_input) + .with_options(options) .aggregate(new_group_by_exprs, agg_expr)? .build() } @@ -1262,21 +1179,11 @@ impl SqlToRel<'_, S> { aggr_exprs: &[Expr], ) -> Result { // create the aggregate plan - let required_output_columns = required_aggregate_output_columns( - input.schema(), - select_exprs, - having_expr_opt, - qualify_expr_opt, - order_by_exprs, - on_exprs, - )?; - let group_by_exprs = add_required_group_by_exprs_from_dependencies( - group_by_exprs.to_vec(), - input.schema(), - &required_output_columns, - )?; + let options = + LogicalPlanBuilderOptions::new().with_add_implicit_group_by_exprs(true); let plan = LogicalPlanBuilder::from(input.clone()) - .aggregate(group_by_exprs, aggr_exprs.to_vec())? + .with_options(options) + .aggregate(group_by_exprs.to_vec(), aggr_exprs.to_vec())? .build()?; let group_by_exprs = if let LogicalPlan::Aggregate(agg) = &plan { &agg.group_expr diff --git a/datafusion/sqllogictest/test_files/group_by.slt b/datafusion/sqllogictest/test_files/group_by.slt index 6968156e59b17..8c055c25caeb2 100644 --- a/datafusion/sqllogictest/test_files/group_by.slt +++ b/datafusion/sqllogictest/test_files/group_by.slt @@ -3602,7 +3602,7 @@ SELECT column1, COUNT(*) as column2 FROM (VALUES (['a', 'b'], 1), (['c', 'd', 'e # primary key should be aware from which columns it is associated -statement error DataFusion error: Error during planning: Column in SELECT must be in GROUP BY or an aggregate function: While expanding wildcard, column "r\.sn" must appear in the GROUP BY clause or must be part of an aggregate function, currently only "l\.sn, sum\(l\.amount\)" appears in the SELECT clause satisfies this requirement +statement error DataFusion error: Error during planning: Column in SELECT must be in GROUP BY or an aggregate function: While expanding wildcard, column "r\.sn" must appear in the GROUP BY clause or must be part of an aggregate function, currently only "l\.sn, l\.zip_code, l\.country, l\.ts, l\.currency, l\.amount, sum\(l\.amount\)" appears in the SELECT clause satisfies this requirement SELECT l.sn, r.sn, SUM(l.amount), r.amount FROM sales_global_with_pk AS l JOIN sales_global_with_pk AS r @@ -3692,7 +3692,7 @@ ORDER BY r.sn 4 100 2022-01-03T10:00:00 # after join, new window expressions shouldn't be associated with primary keys -statement error DataFusion error: Error during planning: Column in SELECT must be in GROUP BY or an aggregate function: While expanding wildcard, column "rn1" must appear in the GROUP BY clause or must be part of an aggregate function, currently only "r\.sn, sum\(r\.amount\)" appears in the SELECT clause satisfies this requirement +statement error DataFusion error: Error during planning: Column in SELECT must be in GROUP BY or an aggregate function: While expanding wildcard, column "rn1" must appear in the GROUP BY clause or must be part of an aggregate function, currently only "r\.sn, r\.ts, r\.amount, sum\(r\.amount\)" appears in the SELECT clause satisfies this requirement SELECT r.sn, SUM(r.amount), rn1 FROM (SELECT r.ts, r.sn, r.amount, diff --git a/datafusion/sqllogictest/test_files/group_by_fd_prune.slt b/datafusion/sqllogictest/test_files/group_by_fd_prune.slt deleted file mode 100644 index 16c65b4c559f0..0000000000000 --- a/datafusion/sqllogictest/test_files/group_by_fd_prune.slt +++ /dev/null @@ -1,121 +0,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. - -# Functional-dependency targets should only be added to aggregate -# GROUP BY outputs when the SQL query actually needs them after -# aggregation. - -statement ok -CREATE TABLE fd_group_by_pk ( - id INT, - name VARCHAR, - amount FLOAT, - PRIMARY KEY(id) -) AS VALUES - (1, 'a', 10.0), - (2, 'b', 20.0), - (3, 'c', 30.0) - -statement ok -set datafusion.explain.logical_plan_only = true; - -# Unreferenced columns determined by the primary key are not appended -# to the aggregate group keys. -query TT -EXPLAIN SELECT id, SUM(amount) -FROM fd_group_by_pk -GROUP BY id -ORDER BY id ----- -logical_plan -01)Sort: fd_group_by_pk.id ASC NULLS LAST -02)--Aggregate: groupBy=[[fd_group_by_pk.id]], aggr=[[sum(CAST(fd_group_by_pk.amount AS Float64))]] -03)----TableScan: fd_group_by_pk projection=[id, amount] - -# SELECT references to functionally-dependent columns still make -# those columns available after aggregation. -query TT -EXPLAIN SELECT id, name, SUM(amount) -FROM fd_group_by_pk -GROUP BY id -ORDER BY id ----- -logical_plan -01)Sort: fd_group_by_pk.id ASC NULLS LAST -02)--Aggregate: groupBy=[[fd_group_by_pk.id, fd_group_by_pk.name]], aggr=[[sum(CAST(fd_group_by_pk.amount AS Float64))]] -03)----TableScan: fd_group_by_pk projection=[id, name, amount] - -# HAVING references to functionally-dependent columns also keep them -# available for the post-aggregate filter. -query TT -EXPLAIN SELECT id, SUM(amount) -FROM fd_group_by_pk -GROUP BY id -HAVING name IS NOT NULL OR SUM(amount) > 0 -ORDER BY id ----- -logical_plan -01)Sort: fd_group_by_pk.id ASC NULLS LAST -02)--Projection: fd_group_by_pk.id, sum(fd_group_by_pk.amount) -03)----Filter: fd_group_by_pk.name IS NOT NULL OR sum(fd_group_by_pk.amount) > Float64(0) -04)------Aggregate: groupBy=[[fd_group_by_pk.id, fd_group_by_pk.name]], aggr=[[sum(CAST(fd_group_by_pk.amount AS Float64))]] -05)--------TableScan: fd_group_by_pk projection=[id, name, amount] - -# ORDER BY references to functionally-dependent columns keep them -# available as hidden aggregate outputs. -query TT -EXPLAIN SELECT id, SUM(amount) -FROM fd_group_by_pk -GROUP BY id -ORDER BY name ----- -logical_plan -01)Projection: fd_group_by_pk.id, sum(fd_group_by_pk.amount) -02)--Sort: fd_group_by_pk.name ASC NULLS LAST -03)----Projection: fd_group_by_pk.id, sum(fd_group_by_pk.amount), fd_group_by_pk.name -04)------Aggregate: groupBy=[[fd_group_by_pk.id, fd_group_by_pk.name]], aggr=[[sum(CAST(fd_group_by_pk.amount AS Float64))]] -05)--------TableScan: fd_group_by_pk projection=[id, name, amount] - -# DISTINCT ON references to functionally-dependent columns also keep -# them available for the post-aggregate distinct grouping. -query TT -EXPLAIN SELECT DISTINCT ON (name) id, SUM(amount) -FROM fd_group_by_pk -GROUP BY id -ORDER BY name ----- -logical_plan -01)Projection: first_value(fd_group_by_pk.id) ORDER BY [fd_group_by_pk.name ASC NULLS LAST] AS id, first_value(sum(fd_group_by_pk.amount)) ORDER BY [fd_group_by_pk.name ASC NULLS LAST] AS sum(fd_group_by_pk.amount) -02)--Sort: fd_group_by_pk.name ASC NULLS LAST -03)----Aggregate: groupBy=[[fd_group_by_pk.name]], aggr=[[first_value(fd_group_by_pk.id) ORDER BY [fd_group_by_pk.name ASC NULLS LAST], first_value(sum(fd_group_by_pk.amount)) ORDER BY [fd_group_by_pk.name ASC NULLS LAST]]] -04)------Aggregate: groupBy=[[fd_group_by_pk.id, fd_group_by_pk.name]], aggr=[[sum(CAST(fd_group_by_pk.amount AS Float64))]] -05)--------TableScan: fd_group_by_pk projection=[id, name, amount] - -# Ordinal grouping still resolves before dependency pruning. -query TT -EXPLAIN SELECT id, SUM(amount) -FROM fd_group_by_pk -GROUP BY 1 -ORDER BY id ----- -logical_plan -01)Sort: fd_group_by_pk.id ASC NULLS LAST -02)--Aggregate: groupBy=[[fd_group_by_pk.id]], aggr=[[sum(CAST(fd_group_by_pk.amount AS Float64))]] -03)----TableScan: fd_group_by_pk projection=[id, amount] - -statement ok -RESET datafusion.explain.logical_plan_only;