xuzifu666 commented on code in PR #5052:
URL: https://github.com/apache/calcite/pull/5052#discussion_r3485117484


##########
core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java:
##########
@@ -5658,6 +5665,269 @@ protected RelDataType validateSelectList(final 
SqlNodeList selectItems,
     return typeFactory.createStructType(fieldList);
   }
 
+  /**
+   * Rewrites scalar sub-queries in the SELECT list whose single select item is
+   * an aggregate function whose arguments reference only outer columns. Per 
the
+   * SQL standard, such aggregates belong to the outer query.
+   *
+   * <p>The algorithm is:
+   * <ol>
+   * <li>For each item in the SELECT list, check whether it is a scalar
+   * sub-query, optionally wrapped in {@code AS} or {@code WITH}.
+   * <li>Inside the sub-query, require the SELECT list to contain exactly one
+   * item, and that item to be an aggregate function call.
+   * <li>Require every argument of the aggregate to reference only columns from
+   * the outer query (no inner columns), and to contain no nested sub-queries.
+   * <li>If all conditions hold, lift the aggregate out of the sub-query: keep
+   * the aggregate in the outer SELECT list, and replace the original sub-query
+   * with {@code (SELECT 1 FROM ... LIMIT 1)}. The result is equivalent because
+   * the scalar sub-query contributes a factor of one per outer row, while the
+   * aggregate is evaluated over the outer rows.
+   * <li>If the outer query becomes an aggregate query as a result, upgrade its
+   * SELECT clause scope from {@link SelectScope} to
+   * {@link AggregatingSelectScope}.
+   * </ol>
+   *
+   * <p>For example,
+   * <blockquote><pre>SELECT (SELECT sum(a) FROM t LIMIT 1) FROM 
aa</pre></blockquote>

Review Comment:
   OK, The Javadoc examples for `rewriteOuterAggregatesInSelectList` have been 
improved, explicitly stating that `a` comes from `aa` and `x` comes from `t`.
   Boundary tests have been added to `agg.iq`: Inner table empty → 1 row NULL
   Outer table empty → 1 row NULL (because the outer aggregation has no input 
rows)
   and postgresql test also updated (result is also keep the same with agg.iq) 
https://onecompiler.com/postgresql/44tgmwq6p



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

Reply via email to