Class RewriteSumOfExpressionPlusConstant


public class RewriteSumOfExpressionPlusConstant extends OptimizerRules.ParameterizedOptimizerRule<Aggregate,LogicalOptimizerContext>
Rewrites two or more SUM(x ± c) expressions over the same non-foldable expression x into SUM(SINGLE_VALUE_OR_NULL(x)) ± c * COUNT(SINGLE_VALUE_OR_NULL(x)), decomposing the per-row arithmetic into separate aggregations on the shared expression:
     STATS s1 = SUM(x + 1), s2 = SUM(x - 2) BY g
     →
     EVAL _sv = SINGLE_VALUE_OR_NULL(x)
     | STATS _sv_sum = SUM(_sv), _sv_count = COUNT(_sv) BY g
     | EVAL s1 = _sv_sum + 1 * _sv_count, s2 = _sv_sum - 2 * _sv_count
     | PROJECT s1, s2, g
 

x can be any non-foldable expression (a field reference, a function call, etc.). Two SUM expressions share a SUM(sv)/COUNT(sv) pair when they are simple sums (no filter, no window) whose x operands are canonically equal. Supported forms: SUM(x ± c) and SUM(c ± x), where exactly one operand is foldable (the constant c) and the other is not.

This rule must run before ReplaceAggregateNestedExpressionWithEval, which would extract x ± c into a pre-agg EVAL, hiding the pattern from this rule.

Filtered aggregates (SUM(x + 1) WHERE y > z) are excluded because they operate on a subset of rows and cannot share a base SUM(sv)/COUNT(sv) with other aggregates.