@@ -107,6 +107,8 @@ export class ClickHousePrinter {
107107 private tableContexts : Map < string , TableSchema > = new Map ( ) ;
108108 /** Column metadata collected during SELECT processing */
109109 private outputColumns : OutputColumnMetadata [ ] = [ ] ;
110+ /** Whether we're currently processing GROUP BY expressions */
111+ private inGroupByContext = false ;
110112
111113 constructor (
112114 private context : PrinterContext ,
@@ -359,7 +361,15 @@ export class ClickHousePrinter {
359361 // Process other clauses
360362 const prewhere = node . prewhere ? this . visit ( node . prewhere ) : null ;
361363 const whereStr = where ? this . visit ( where ) : null ;
362- const groupBy = node . group_by ? node . group_by . map ( ( col ) => this . visit ( col ) ) : null ;
364+
365+ // Process GROUP BY with context flag to use raw columns for whereTransform columns
366+ let groupBy : string [ ] | null = null ;
367+ if ( node . group_by ) {
368+ this . inGroupByContext = true ;
369+ groupBy = node . group_by . map ( ( col ) => this . visit ( col ) ) ;
370+ this . inGroupByContext = false ;
371+ }
372+
363373 const having = node . having ? this . visit ( node . having ) : null ;
364374 const orderBy = node . order_by ? node . order_by . map ( ( col ) => this . visit ( col ) ) : null ;
365375
@@ -1669,9 +1679,16 @@ export class ClickHousePrinter {
16691679 }
16701680
16711681 /**
1672- * Check if we're currently inside a comparison operation (WHERE context)
1682+ * Check if we're in a context where we should use raw column names
1683+ * instead of virtual column expressions (WHERE comparisons or GROUP BY)
16731684 */
16741685 private isInComparisonContext ( ) : boolean {
1686+ // Check if we're in GROUP BY context
1687+ if ( this . inGroupByContext ) {
1688+ return true ;
1689+ }
1690+
1691+ // Check if we're inside a comparison operation (WHERE/HAVING context)
16751692 for ( const node of this . stack ) {
16761693 if ( ( node as CompareOperation ) . expression_type === "compare_operation" ) {
16771694 return true ;
0 commit comments