crepererum opened a new issue, #6116: URL: https://github.com/apache/arrow-datafusion/issues/6116
### Describe the bug `common_sub_expression_eliminate` pushes aggregate expressions into a child of the aggregate note which is wrong. ### To Reproduce See https://github.com/apache/arrow-datafusion/blob/0d93dede46aae547d0ac167aa3e3e502efdffb97/datafusion/optimizer/src/common_subexpr_eliminate.rs#L707-L728 ### Expected behavior ```rust let expected = "Projection: Int32(1) + AVG(test.a), Int32(1) - AVG(test.a)\ \n Aggregate: groupBy=[[]], aggr=[[AVG(test.a) AS AVG(test.a)]]\ \n TableScan: test"; ``` In general it should push the expression used within aggregate (and aggregate UDFs) into a child while placing the users of the aggregates into a parent. So a more complex test case may look like this: ```rust #[test] fn aggregate() -> Result<()> { let table_scan = test_table_scan()?; let inner = binary_expr(lit(1), Operator::Plus, avg(col("a"))); let plan = LogicalPlanBuilder::from(table_scan) .aggregate( iter::empty::<Expr>(), vec![ binary_expr(lit(1), Operator::Plus, avg(inner)), binary_expr(lit(1), Operator::Minus, avg(inner)), min(inner), ], )? .build()?; let expected = "Projection: Int32(1) + AVG(TMP), Int32(1) - AVG(TMP), MIN(TMP)\ \n Aggregate: groupBy=[[]], aggr=[[AVG(TMP) as AVG(TMP), MIN(TMP) as MIN(TMP)]]\ \n Projection: Int32(1) + test.a AS TMP, test.a, test.b, test.c\ \n TableScan: test"; assert_optimized_plan_eq(expected, &plan); Ok(()) } ``` (I somewhat improvised the column naming here to be able to write this down quicker) ### Additional context For SQL queries this doesn't seem to be an issue because this kind of de-duplication seems already be done during lowering, e.g. this code ```sql SELECT AVG(c1 + 1) + 1, AVG(c1 + 1) + 2 FROM test ``` produces this initial plan: ```text Projection: AVG(test.c1 + Int64(1)) + Int64(1), AVG(test.c1 + Int64(1)) + Int64(2) Aggregate: groupBy=[[]], aggr=[[AVG(test.c1 + Int64(1))]] TableScan: test ``` -- 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]
