xuzifu666 commented on code in PR #5052: URL: https://github.com/apache/calcite/pull/5052#discussion_r3484959925
########## core/src/test/resources/sql/agg.iq: ########## @@ -4301,4 +4301,29 @@ GROUP BY GROUPING SETS ((deptno), ()); !ok +# [CALCITE-6104] Aggregate function that references outer column should be evaluated in outer query Review Comment: Thanks for the reminder, I had added comment about it and the test case had been added. But agg.iq to verify the correctness of the numerical results calculated after the Calcite fix within PostgreSQL, the original SQL must be rewritten into standard SQL supported by PostgreSQL. Validated these sql in https://onecompiler.com/postgresql/44tgmwq6p and result is as expected. ########## core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java: ########## @@ -5658,6 +5665,251 @@ 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>For example, + * <blockquote><pre>SELECT (SELECT sum(a) FROM t LIMIT 1) FROM aa</pre></blockquote> + * is rewritten to + * <blockquote><pre>SELECT sum(a) * (SELECT 1 FROM t LIMIT 1) FROM aa</pre></blockquote> Review Comment: Okay, I’ve added the logic for the overall process; I hope that clarifies things. ########## core/src/test/resources/sql/agg.iq: ########## @@ -4301,4 +4301,29 @@ GROUP BY GROUPING SETS ((deptno), ()); !ok +# [CALCITE-6104] Aggregate function that references outer column should be evaluated in outer query +WITH aa (a) AS (VALUES 1, 2, 3), + xx (x) AS (VALUES 10, 20, 30) +SELECT (SELECT sum(a) FROM xx LIMIT 1) AS sa +FROM aa; ++----+ +| SA | ++----+ +| 6 | ++----+ +(1 row) + +!ok + +SELECT (SELECT sum(sal) FROM dept) AS sum_sal Review Comment: Yes, I review the blog overall and add new case for it. The correspondence is as follows: ``` SELECT (SELECT sum(1) FROM xx LIMIT 1) FROM aa ``` Aggregate with no column references aggregates at the innermost level. ``` SELECT (SELECT sum(a) FROM xx LIMIT 1) FROM aa ``` Aggregate function that references outer column should be evaluated in outer query. ``` SELECT (SELECT sum(x) FROM xx LIMIT 1) FROM aa ``` Aggregate referencing only inner column aggregates at the inner level. -- 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]
