summaryrefslogtreecommitdiffstats
path: root/sqlglot/optimizer/pushdown_projections.py
diff options
context:
space:
mode:
Diffstat (limited to 'sqlglot/optimizer/pushdown_projections.py')
-rw-r--r--sqlglot/optimizer/pushdown_projections.py9
1 files changed, 6 insertions, 3 deletions
diff --git a/sqlglot/optimizer/pushdown_projections.py b/sqlglot/optimizer/pushdown_projections.py
index 2e51117..be3ddb2 100644
--- a/sqlglot/optimizer/pushdown_projections.py
+++ b/sqlglot/optimizer/pushdown_projections.py
@@ -39,8 +39,9 @@ def pushdown_projections(expression, schema=None, remove_unused_selections=True)
for scope in reversed(traverse_scope(expression)):
parent_selections = referenced_columns.get(scope, {SELECT_ALL})
- if scope.expression.args.get("distinct"):
- # We can't remove columns SELECT DISTINCT nor UNION DISTINCT
+ if scope.expression.args.get("distinct") or scope.parent and scope.parent.pivots:
+ # We can't remove columns SELECT DISTINCT nor UNION DISTINCT. The same holds if
+ # we select from a pivoted source in the parent scope.
parent_selections = {SELECT_ALL}
if isinstance(scope.expression, exp.Union):
@@ -105,7 +106,9 @@ def _remove_unused_selections(scope, parent_selections, schema):
for name in sorted(parent_selections):
if name not in names:
- new_selections.append(alias(exp.column(name, table=resolver.get_table(name)), name))
+ new_selections.append(
+ alias(exp.column(name, table=resolver.get_table(name)), name, copy=False)
+ )
# If there are no remaining selections, just select a single constant
if not new_selections: