Uploaded image for project: 'Calcite'
  1. Calcite
  2. CALCITE-3466

JDBC adapter incorrectly drops GROUP BY clause of sub-query

    XMLWordPrintableJSON

Details

    Description

      While convert RelNode to SqlNode, the "group by" statement in subquery was dropped unexpectedly. For example,
      original sql is:

      select a, avg(c1) from 
      (
          select a,sum(d),b as c1 from t group by b,a
      ) as t 
      group by a
      

      RelNode converted by SqlNode is

      LogicalAggregate(group=[{0}], EXPR$1=[AVG($1)])
        LogicalProject(A=[$1], C1=[$0])
          LogicalAggregate(group=[{0, 1}], EXPR$1=[SUM($2)])
            LogicalProject(B=[$1], A=[$0], D=[$3])
              EnumerableTableScan(table=[[T_TESTPROJECTMERGE]])
      

      And then convert this RelNode to SqlNode, the sql of SqlNode is like this:

      SELECT `A`, AVG(`B`)
      FROM `T`
      GROUP BY `A`
      

      We can find that "group by" in subquery was dropped which may cause SqlNode converted by RelNode being not equivalent to RelNode.

      After debugging, I've found code
      at https://github.com/apache/calcite/blob/aa98c1575762718b238af8ddd44a390607de7602/core/src/main/java/org/apache/calcite/rel/rel2sql/RelToSqlConverter.java#L333
      calls org.apache.calcite.rel.rel2sql.SqlImplementor.Builder#setGroupBy without judge whether "group by" already exists.
      Finally, I think in this case, the main select and sub-select shouldn't be merged.

      Attachments

        1. screenshot-1.png
          117 kB
          Wang Weidong

        Issue Links

          Activity

            People

              wangweidong Wang Weidong
              wangweidong Wang Weidong
              Votes:
              0 Vote for this issue
              Watchers:
              5 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved:

                Time Tracking

                  Estimated:
                  Original Estimate - Not Specified
                  Not Specified
                  Remaining:
                  Remaining Estimate - 0h
                  0h
                  Logged:
                  Time Spent - 8h 40m
                  8h 40m