cloud-fan commented on code in PR #55925:
URL: https://github.com/apache/spark/pull/55925#discussion_r3646777324
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteDistinctAggregates.scala:
##########
@@ -419,6 +421,48 @@ object RewriteDistinctAggregates extends Rule[LogicalPlan]
{
}
}
+ /**
+ * Canonicalizes COUNT(DISTINCT IF(cond, base, NULL)) and
+ * COUNT(DISTINCT CASE WHEN cond THEN base END) to COUNT(DISTINCT base)
FILTER (WHERE cond).
+ * This reduces the number of distinct groups: multiple conditional counts
on the same base
+ * column collapse into one group, shrinking the Expand fan-out from Nx to
1x.
+ */
+ private def normalizeCountDistinctConditional(a: Aggregate): Aggregate = {
+ if (!SQLConf.get.rewriteCountDistinctConditionalEnabled) return a
+ a.transformExpressionsUpWithPruning(
+ _.containsAnyPattern(IF, CASE_WHEN)) {
+ case ae @ AggregateExpression(count: Count, _, true, None, _)
+ if count.children.size == 1 =>
+ extractCondAndBase(count.children.head) match {
+ case Some((cond, base)) =>
+ ae.copy(
+ aggregateFunction = Count(base),
Review Comment:
This changes more than the distinct-group shape: it removes the
conditional's short-circuiting. `Expand` now evaluates `base` as a grouping
projection even when `cond` is false or null, so an expression that was
previously unreachable (for example, division by zero under ANSI mode) can make
a valid query fail. Please preserve the conditional around the projected value,
or restrict the rewrite to expressions safe to evaluate outside the branch, and
add a two-count regression test that reaches `rewrite()`.
--
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]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]