Module group_by_alias_expander

Module group_by_alias_expander 

Source
Expand description

GROUP BY clause alias expansion transformer

This transformer allows users to reference SELECT clause aliases in GROUP BY clauses by automatically expanding those aliases to their full expressions.

§Problem

Users often want to group by a complex expression using its alias:

SELECT id % 3 as grp, COUNT(*) FROM t GROUP BY grp

This fails because GROUP BY is evaluated before SELECT, so aliases don’t exist yet.

§Solution

The transformer rewrites to:

SELECT id % 3 as grp, COUNT(*) FROM t GROUP BY id % 3

§Algorithm

  1. Extract all aliases from SELECT clause and their corresponding expressions
  2. Scan GROUP BY clause for column references
  3. If a column reference matches an alias name, replace it with the full expression
  4. Only expand simple column references (not qualified table.column)

§Limitations

  • Only works for simple column aliases (not table.alias references)
  • Aliases take precedence over actual column names if they conflict
  • Complex expressions are duplicated (no common subexpression elimination)

Structs§

GroupByAliasExpander
Transformer that expands SELECT aliases in GROUP BY clauses