asolimando commented on code in PR #4494:
URL: https://github.com/apache/calcite/pull/4494#discussion_r2259794264


##########
core/src/main/java/org/apache/calcite/rel/rules/IntersectToDistinctRule.java:
##########
@@ -126,12 +143,86 @@ public IntersectToDistinctRule(Class<? extends Intersect> 
intersectClass,
     call.transformTo(relBuilder.build());
   }
 
+  /**
+   * Variant performing a partial aggregation pushdown.
+   *
+   * <p>Original query:
+   * <pre>{@code
+   * SELECT job FROM "scott".emp WHERE deptno = 10
+   * INTERSECT
+   * SELECT job FROM "scott".emp WHERE deptno = 20
+   * }</pre>
+   *
+   * <p>Query after conversion:
+   * <pre>{@code
+   * SELECT job
+   * FROM (
+   *   SELECT job, SUM(c)
+   *   FROM (
+   *     SELECT job, COUNT(*) AS c FROM "scott".emp
+   *     WHERE deptno = 10 GROUP BY job
+   *     UNION ALL
+   *     SELECT job, COUNT(*) AS c FROM "scott".emp
+   *     WHERE deptno = 20 GROUP BY job)
+   *   GROUP BY job)
+   * WHERE c = 2
+   * }</pre>
+   */
+  public void onMatchAggregatePushdown(RelOptRuleCall call) {
+    final Intersect intersect = call.rel(0);
+    if (intersect.all) {
+      return; // nothing we can do
+    }
+    final RelOptCluster cluster = intersect.getCluster();
+    final RexBuilder rexBuilder = cluster.getRexBuilder();
+    final RelBuilder relBuilder = call.builder();
+
+    // 1st level aggregate: create an aggregate(col0, col1, count() as c) for 
each branch
+    for (RelNode input : intersect.getInputs()) {
+      relBuilder.push(input);
+      relBuilder.aggregate(relBuilder.groupKey(relBuilder.fields()),
+          relBuilder.countStar(null));

Review Comment:
   I haven't re-checked the logic of the original rule as it's out of scope for 
the current PR (removing the plan regression introduced by CALCITE-6893), so 
it's possible that there are further improvements that can be made, but this 
should be discussed in a new, dedicated ticket.



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