Skip to content

[SPARK-59175][SQL] Extract the whole GROUP BY expression when a select item combines it with a window function - #58544

Open
hemanthboyina wants to merge 1 commit into
apache:masterfrom
hemanthboyina:SPARK-59175-window-groupby-missing-agg
Open

[SPARK-59175][SQL] Extract the whole GROUP BY expression when a select item combines it with a window function#58544
hemanthboyina wants to merge 1 commit into
apache:masterfrom
hemanthboyina:SPARK-59175-window-groupby-missing-agg

Conversation

@hemanthboyina

Copy link
Copy Markdown

What changes were proposed in this pull request?

When a select item mixes a window function with the GROUP BY expression (e.g. CASE WHEN ROW_NUMBER() OVER (...) <= 2 THEN UPPER(country) ... END with GROUP BY UPPER(country)), the ExtractWindowExpressions rule builds an Aggregate under the Window and decides which inputs the Aggregate must output.

While scanning that select item, the rule had no case for a plain expression like UPPER(country), so it looked inside it and pushed down the raw column country instead of the whole UPPER(country). The resulting Aggregate outputs a country column that is not in the GROUP BY, which is an invalid plan.

This PR passes the grouping expressions to extract and adds a case that pushes a sub-expression down as a whole when it matches a grouping expression. The Aggregate now outputs UPPER(country) instead of country. Bare grouping columns keep their existing behavior, so only queries that used to fail are affected.

Why are the changes needed?

The query is valid SQL but fails analysis with:
[MISSING_AGGREGATION] The non-aggregating expression "country" is based on columns which are not participating in the GROUP BY clause. SQLSTATE: 42803

This is wrong: country is never selected directly, only UPPER(country), which is the GROUP BY expression.

Does this PR introduce any user-facing change?

Yes. A query that combines a window function with the GROUP BY expression in the same select item used to fail with MISSING_AGGREGATION; it now runs and returns the correct result. Queries that already
worked are unaffected.

How was this patch tested?

Added a test in DataFrameWindowFunctionsSuite covering the reported query plus two regression cases (grouping by the bare column, and the window function in a separate select item).

Was this patch authored or co-authored using generative AI tooling?

No

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant