Skip to content

Fix HAVING clause to accept SELECT aliases (#887) - #2558

Open
harsh-thakkar7 wants to merge 1 commit into
AlaSQL:developfrom
harsh-thakkar7:fix/887-having-alias
Open

harsh-thakkar7 wants to merge 1 commit into
AlaSQL:developfrom
harsh-thakkar7:fix/887-having-alias

Conversation

@harsh-thakkar7

Copy link
Copy Markdown

Description

Restores support for referencing SELECT aliases inside the HAVING clause, which the wiki documents and which regressed.

Given:

alasql('SELECT Country, COUNT(*) AS cnt FROM City GROUP BY Country HAVING cnt > 2');

the query used to return the groups with more than two rows; it currently returns [] because the HAVING expression cnt > 2 compiles to g['cnt'] while groups accumulate under the aggregate's key (COUNT(*)), so the comparison always evaluates against undefined.

Root cause

HAVING is evaluated per group (in src/38query.js) before the SELECT list is materialized, so output aliases are not directly visible there. compileHaving (src/425having.js) compiles the raw expression against the group row without resolving alias references.

Fix

yy.Select.prototype.compileHaving now rewrites unqualified column references in the HAVING expression to the corresponding group-accumulation key using query.groupColumns (the same alias → nick mapping used to build the SELECT output). The rewrite clones the expression nodes, so the shared AST is untouched and column-reference behaviour elsewhere is unchanged.

Resolves #887

Changes

  • src/425having.js — resolve SELECT aliases referenced in HAVING (resolveHavingAliases).
  • test/test1277.js — new tests:
    • HAVING with COUNT(*) AS cnt alias
    • HAVING alias in a SELECT *, ... query (the exact case from the issue)
    • HAVING with a SUM() AS popsum alias
    • plain aggregator HAVING COUNT(*) > 2 still works

Verification

  • bun test ./test/test1277.js — 4/4 passing.
  • Full suite: bun test ./test/test[0-9]*.js ./test/test-*.js — 2240 pass, 5 fail. The 5 failures (Test 147 / 220 / 334 / 404, all WITH/CTE-related) are pre-existing and order-dependent — identical on a clean develop checkout and unrelated to this change.
  • yarn test-format passes.

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.

Alias on HAVING clause not working properly

1 participant