diff options
Diffstat (limited to 'sqlglot/optimizer/merge_subqueries.py')
-rw-r--r-- | sqlglot/optimizer/merge_subqueries.py | 18 |
1 files changed, 18 insertions, 0 deletions
diff --git a/sqlglot/optimizer/merge_subqueries.py b/sqlglot/optimizer/merge_subqueries.py index 3e435f5..3c51c18 100644 --- a/sqlglot/optimizer/merge_subqueries.py +++ b/sqlglot/optimizer/merge_subqueries.py @@ -119,6 +119,23 @@ def _mergeable(outer_scope, inner_select, leave_tables_isolated, from_or_join): Returns: bool: True if can be merged """ + + 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 + unmergable_window_columns = [ + column + for column in outer_scope.columns + if column.find_ancestor(exp.Where, exp.Group, exp.Order, exp.Join, exp.Having, exp.AggFunc) + ] + window_expressions_in_unmergable = [ + column + for column in unmergable_window_columns + if column.table == inner_select_name and column.name in window_alias_names + ] + return any(window_expressions_in_unmergable) + return ( isinstance(outer_scope.expression, exp.Select) and isinstance(inner_select, exp.Select) @@ -137,6 +154,7 @@ def _mergeable(outer_scope, inner_select, leave_tables_isolated, from_or_join): and inner_select.args.get("where") and any(j.side in {"FULL", "RIGHT"} for j in outer_scope.expression.args.get("joins", [])) ) + and not _is_a_window_expression_in_unmergable_operation() ) |