Skip to content

Commit

Permalink
fix(optimizer): merge subqueries should use alias from outer scope (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
barakalon authored Sep 8, 2023
1 parent 981ad23 commit d192515
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
2 changes: 1 addition & 1 deletion sqlglot/optimizer/merge_subqueries.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ def _mergeable(outer_scope, inner_scope, leave_tables_isolated, from_or_join):
def _is_a_window_expression_in_unmergable_operation():
window_expressions = inner_select.find_all(exp.Window)
window_alias_names = {window.parent.alias_or_name for window in window_expressions}
inner_select_name = inner_select.parent.alias_or_name
inner_select_name = from_or_join.alias_or_name
unmergable_window_columns = [
column
for column in outer_scope.columns
Expand Down
15 changes: 15 additions & 0 deletions tests/fixtures/optimizer/merge_subqueries.sql
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,21 @@ FROM
t1;
SELECT x.a AS a, x.b AS b, ROW_NUMBER() OVER (PARTITION BY x.a ORDER BY x.a) AS row_num FROM x AS x;

# title: Don't merge window functions, inner table is aliased in outer query
with t1 as (
SELECT
ROW_NUMBER() OVER (PARTITION BY x.a ORDER BY x.a) as row_num
FROM
x
)
SELECT
t2.row_num
FROM
t1 AS t2
WHERE
t2.row_num = 2;
WITH t1 AS (SELECT ROW_NUMBER() OVER (PARTITION BY x.a ORDER BY x.a) AS row_num FROM x AS x) SELECT t2.row_num AS row_num FROM t1 AS t2 WHERE t2.row_num = 2;

# title: Values Test
# dialect: spark
WITH t1 AS (
Expand Down

0 comments on commit d192515

Please sign in to comment.