Apache DataFusion SQL Query Engine
GROUP-BY prioritizes input columns in case of ambiguity (#9228)
Jonah Gao40353fe44425
diff --git a/datafusion/sql/src/select.rs b/datafusion/sql/src/select.rsindex 7862715e5f..f47720d467 100644--- a/datafusion/sql/src/select.rs+++ b/datafusion/sql/src/select.rs@@ -88,8 +88,11 @@ impl<'a, S: ContextProvider> SqlToRel<'a, S> {// having and group by clause may reference aliases defined in select projectionlet projected_plan = self.project(base_plan.clone(), select_exprs.clone())?;- let mut combined_schema = (**projected_plan.schema()).clone();- combined_schema.merge(base_plan.schema());+ // Place the fields of the base plan at the front so that when there are references+ // with the same name, the fields of the base plan will be searched first.+ // See https://github.com/apache/arrow-datafusion/issues/9162+ let mut combined_schema = base_plan.schema().as_ref().clone();+ combined_schema.merge(projected_plan.schema());// this alias map is resolved and looked up in both having exprs and group by exprslet alias_map = extract_aliases(&select_exprs);diff --git a/datafusion/sqllogictest/test_files/aggregate.slt b/datafusion/sqllogictest/test_files/aggregate.sltindex 136fb39c67..f50134e635 100644--- a/datafusion/sqllogictest/test_files/aggregate.slt+++ b/datafusion/sqllogictest/test_files/aggregate.slt@@ -3179,3 +3179,23 @@ NULLstatement okDROP TABLE t;++# Test for the case when the column name is ambiguous+statement ok+CREATE TABLE t(a BIGINT) AS VALUES(1), (2), (3);++# The column name referenced by GROUP-BY is ambiguous, prefer the column in base plan+query I+SELECT 0 as "t.a" FROM t GROUP BY t.a;+----+0+0+0++# The column name referenced by HAVING is ambiguous, prefer the column in the base plan+query I+SELECT 0 AS "t.a" FROM t HAVING MAX(t.a) = 0;+----++statement ok+DROP TABLE t;\ No newline at end of file