@@ -829,17 +829,40 @@ impl Unparser<'_> {
829829 select. already_projected ( ) ,
830830 ) ?;
831831
832- // If the SubqueryAlias directly wraps a plan that builds its
833- // own SELECT clauses (e.g. Aggregate adds GROUP BY, Window adds
832+ // If the (possibly rewritten) inner plan builds its own
833+ // SELECT clauses (e.g. Aggregate adds GROUP BY, Window adds
834834 // OVER, etc.) and unparse_table_scan_pushdown couldn't reduce it,
835835 // we must emit a derived subquery: (SELECT ...) AS alias.
836836 // Without this, the recursive handler would merge those clauses
837837 // into the outer SELECT, losing the subquery structure entirely.
838- if unparsed_table_scan. is_none ( )
839- && Self :: requires_derived_subquery ( plan_alias. input . as_ref ( ) )
838+ if unparsed_table_scan. is_none ( ) && Self :: requires_derived_subquery ( plan)
840839 {
840+ // When the dialect does not support column aliases in
841+ // table aliases (e.g. SQLite), inject the aliases into
842+ // the inner projection before wrapping as a derived
843+ // subquery.
844+ if !columns. is_empty ( )
845+ && !self . dialect . supports_column_alias_in_table_alias ( )
846+ {
847+ let Ok ( rewritten_plan) =
848+ inject_column_aliases_into_subquery ( plan. clone ( ) , columns)
849+ else {
850+ return internal_err ! (
851+ "Failed to transform SubqueryAlias plan"
852+ ) ;
853+ } ;
854+ return self . derive (
855+ & rewritten_plan,
856+ relation,
857+ Some ( self . new_table_alias (
858+ plan_alias. alias . table ( ) . to_string ( ) ,
859+ vec ! [ ] ,
860+ ) ) ,
861+ false ,
862+ ) ;
863+ }
841864 return self . derive (
842- & plan_alias . input ,
865+ plan ,
843866 relation,
844867 Some ( self . new_table_alias (
845868 plan_alias. alias . table ( ) . to_string ( ) ,
0 commit comments