Mihai Budiu created CALCITE-7974:
------------------------------------

             Summary: RelDecorrelator loses the WITHIN GROUP sort order in a 
correlated sub-query
                 Key: CALCITE-7974
                 URL: https://issues.apache.org/jira/browse/CALCITE-7974
             Project: Calcite
          Issue Type: Bug
          Components: core
    Affects Versions: 1.42.0
            Reporter: Mihai Budiu
            Assignee: Mihai Budiu


Example (scott schema):
{code:sql}
SELECT d.deptno,
  (SELECT LISTAGG(e.ename) WITHIN GROUP (ORDER BY e.ename DESC)
   FROM emp e WHERE e.deptno = d.deptno) AS names
FROM dept d
ORDER BY d.deptno;
{code}
Expected result (Postgres 14 gives the same result for STRING_AGG(e.ename, ',' 
ORDER BY e.ename DESC)):
{noformat}
+--------+--------------------------------------+
| DEPTNO | NAMES                                |
+--------+--------------------------------------+
|     10 | MILLER,KING,CLARK                    |
|     20 | SMITH,SCOTT,JONES,FORD,ADAMS         |
|     30 | WARD,TURNER,MARTIN,JAMES,BLAKE,ALLEN |
|     40 |                                      |
+--------+--------------------------------------+
{noformat}
Actual result (the names are in table order, not in descending order):
{noformat}
+--------+--------------------------------------+
| DEPTNO | NAMES                                |
+--------+--------------------------------------+
|     10 | CLARK,KING,MILLER                    |
|     20 | SMITH,JONES,SCOTT,ADAMS,FORD         |
|     30 | ALLEN,WARD,MARTIN,BLAKE,TURNER,JAMES |
|     40 |                                      |
+--------+--------------------------------------+{noformat}
Cause: RelDecorrelator.decorrelateRel(Aggregate) adds the correlation columns 
to the input of the Aggregate. It remaps the argument list and the filter 
argument of each AggregateCall through combinedMap, but AggregateCall.adaptTo 
keeps the old collation. The old sort key indexes then point to other columns. 
RemoveCorrelationForScalarAggregateRule has the same pattern: it shifts the 
arguments by groupCount, but not the collation. Any aggregate call with a 
collation is affected, for example ARRAY_AGG, COLLECT and LISTAGG.

The top-down decorrelator (topDownGeneralDecorrelationEnabled=true, 
CoreQuidemTest2) gives the expected result.



--
This message was sent by Atlassian Jira
(v10.3.26#10030026)

Reply via email to