diff --git a/sql/src/main/java/io/druid/sql/calcite/rule/SortCollapseRule.java b/sql/src/main/java/io/druid/sql/calcite/rule/SortCollapseRule.java index ae958bac7a5..7549cceb40e 100644 --- a/sql/src/main/java/io/druid/sql/calcite/rule/SortCollapseRule.java +++ b/sql/src/main/java/io/druid/sql/calcite/rule/SortCollapseRule.java @@ -21,7 +21,6 @@ package io.druid.sql.calcite.rule; import org.apache.calcite.plan.RelOptRule; import org.apache.calcite.plan.RelOptRuleCall; -import org.apache.calcite.rel.RelNode; import org.apache.calcite.rel.core.Sort; import org.apache.calcite.rex.RexLiteral; @@ -55,6 +54,7 @@ public class SortCollapseRule extends RelOptRule final int firstOffset = (first.offset != null ? RexLiteral.intValue(first.offset) : 0); final int secondOffset = (second.offset != null ? RexLiteral.intValue(second.offset) : 0); + final int offset = firstOffset + secondOffset; final int fetch; if (first.fetch == null && second.fetch == null) { @@ -76,10 +76,13 @@ public class SortCollapseRule extends RelOptRule ); } - final RelNode combined = call.builder() - .push(first.getInput()) - .sortLimit(firstOffset + secondOffset, fetch, first.getChildExps()) - .build(); + final Sort combined = first.copy( + first.getTraitSet(), + first.getInput(), + first.getCollation(), + offset == 0 ? null : call.builder().literal(offset), + call.builder().literal(fetch) + ); call.transformTo(combined); } diff --git a/sql/src/test/java/io/druid/sql/calcite/CalciteQueryTest.java b/sql/src/test/java/io/druid/sql/calcite/CalciteQueryTest.java index 54c123fbb2c..1ef1fe6d209 100644 --- a/sql/src/test/java/io/druid/sql/calcite/CalciteQueryTest.java +++ b/sql/src/test/java/io/druid/sql/calcite/CalciteQueryTest.java @@ -2075,6 +2075,30 @@ public class CalciteQueryTest ); } + @Test + public void testSelectDistinctWithSortAsOuterQuery4() throws Exception + { + testQuery( + "SELECT * FROM (SELECT DISTINCT dim2 FROM druid.foo ORDER BY dim2 DESC LIMIT 5) LIMIT 10", + ImmutableList.of( + new TopNQueryBuilder() + .dataSource(CalciteTests.DATASOURCE1) + .intervals(QSS(Filtration.eternity())) + .granularity(Granularities.ALL) + .dimension(new DefaultDimensionSpec("dim2", "d0")) + .metric(new InvertedTopNMetricSpec(new DimensionTopNMetricSpec(null, StringComparators.LEXICOGRAPHIC))) + .threshold(5) + .context(QUERY_CONTEXT_DEFAULT) + .build() + ), + ImmutableList.of( + new Object[]{""}, + new Object[]{"abc"}, + new Object[]{"a"} + ) + ); + } + @Test public void testCountDistinct() throws Exception {