xiedeyantu commented on PR #4904:
URL: https://github.com/apache/calcite/pull/4904#issuecomment-4294267932

   During testing, I found that if the `GROUP BY` contains the primary key, 
there is no issue. However, if the `GROUP BY` does not contain the primary key, 
using `SINGLE_VALUE` may cause problems.
   
   Consider the following example:
   
   ```sql
   SELECT
       deptno,
       deptno + 2
   FROM emp
   GROUP BY deptno, deptno + 2
   ORDER BY deptno;
   ```
   
   Since `deptno -> deptno + 2`, according to the current rule, `deptno + 2` 
should be removable. However, execution fails.
   
   If I remove the `GROUP BY` clause from the SQL above, the correct result set 
is:
   
   ```text
    deptno | deptno + 2
   --------+------------
        10 |         12
        10 |         12
        10 |         12
        20 |         22
        20 |         22
        20 |         22
        20 |         22
        20 |         22
        30 |         32
        30 |         32
        30 |         32
        30 |         32
        30 |         32
        30 |         32
   (14 rows)
   ```
   
   If we rewrite it using `SINGLE_VALUE`, the plan becomes:
   
   ```text
   EnumerableSort(sort0=[$0], dir0=[ASC])
     EnumerableAggregate(group=[{0}], EXPR$1=[SINGLE_VALUE($1)])
       EnumerableCalc(expr#0..7=[{inputs}], expr#8=[2], expr#9=[+($t7, $t8)], 
DEPTNO=[$t7], EXPR$1=[$t9])
         EnumerableTableScan(table=[[scott, EMP]])
   ```
   
   During execution, it throws the following error:
   
   ```text
   Caused by: java.lang.IllegalStateException: more than one value in agg 
SINGLE_VALUE
   ```
   
   So my understanding is that the validation of `SINGLE_VALUE` happens before 
aggregation. I think this logic is reasonable: although all values of the 
column (for example, `deptno + 2` in this SQL) are the same, it does not 
actually mean there is only one row, so the exception is expected.
   
   Therefore, I think this rewrite should use `ANY_VALUE` instead of 
`SINGLE_VALUE`.
   


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