carlvinhust2012 commented on code in PR #16442: URL: https://github.com/apache/doris/pull/16442#discussion_r1097321179
########## fe/fe-core/src/main/java/org/apache/doris/analysis/SelectStmt.java: ########## @@ -1291,11 +1291,54 @@ private void analyzeAggregation(Analyzer analyzer) throws AnalysisException { substituteOrdinalsAliases(groupingExprs, "GROUP BY", analyzer, aliasFirst); if (!groupByClause.isGroupByExtension() && !groupingExprs.isEmpty()) { - ArrayList<Expr> tempExprs = new ArrayList<>(groupingExprs); - groupingExprs.removeIf(Expr::isConstant); - if (groupingExprs.isEmpty() && aggExprs.isEmpty()) { - // should keep at least one expr to make the result correct - groupingExprs.add(tempExprs.get(0)); + /* + For performance reason, we want to remove constant column from groupingExprs. + For example: `select 'abc', sum(a) from t group by 'abc'` is equivalent to `select 1, sum(a) from t` + We can remove constant column `abc` from groupingExprs. + But there is an exception: + sql1: `select 'abc' from t group by 'abc'` + sql2: `select 'abc' from t` + sql1 is not equivalent to sql2. + We need to keep some constant column if all items in groupingExprs are constant columns. + Consider sql3 `select a from (select "abc" as a, 'def' as b) T group by b, a;` + if the column is in select list, this column should not be removed. + */ + if (aggExprs.isEmpty()) { + Expr theFirstConstantGroupingExpr = null; + boolean someGroupExprRemoved = false; + ArrayList<Expr> tempExprs = new ArrayList<>(); + for (Expr groupExpr : groupingExprs) { + boolean keep = false; + if (groupExpr.isConstant()) { + if (theFirstConstantGroupingExpr == null) { + theFirstConstantGroupingExpr = groupExpr; + } + for (SelectListItem item : selectList.getItems()) { + if (item.getExpr() instanceof SlotRef) { + keep = ((SlotRef) item.getExpr()).columnEqual(groupExpr); + if (keep) { + break; + } + } + } + } + if (keep) { + tempExprs.add(groupExpr); + } else { + someGroupExprRemoved = true; + } + } + if (someGroupExprRemoved) { + groupingExprs.clear(); + groupingExprs.addAll(tempExprs); + //consider sql1, groupingExprs need at least one expr, it can be + // any original grouping expr. we use the first one. + if (groupingExprs.isEmpty()) { + groupingExprs.add(theFirstConstantGroupingExpr); + } + } + } else { + groupingExprs.removeIf(Expr::isConstant); Review Comment: here, if ‘aggExprs.isEmpty()’ not true,no need add an expr to 'groupingExprs'? -- 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: commits-unsubscr...@doris.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: commits-unsubscr...@doris.apache.org For additional commands, e-mail: commits-h...@doris.apache.org