@@ -629,19 +629,26 @@ def __str__(self):
629629 and (self .limit is not None or self .offset is not None )):
630630 return self ._rownum (str )
631631
632+ ordinals = {}
632633 for expression in chain (
633634 self .group_by or [],
634635 self .order_by or []):
635636 if not isinstance (expression , As ):
636637 continue
637- for column in self .columns :
638+ for i , column in enumerate ( self .columns , start = 1 ) :
638639 if not isinstance (column , As ):
639640 continue
640641 if column .output_name != expression .output_name :
641642 continue
642643 if (str (column .expression ) != str (expression .expression )
643644 or column .params != expression .params ):
644645 raise ValueError ("%r != %r" % (expression , column ))
646+ ordinals [column .output_name ] = i
647+
648+ def str_or_ordinal (expression ):
649+ if isinstance (expression , As ):
650+ expression = ordinals .get (expression .output_name , expression )
651+ return str (expression )
645652
646653 with AliasManager ():
647654 if self .from_ is not None :
@@ -671,7 +678,8 @@ def __str__(self):
671678 where = ' WHERE ' + str (self .where )
672679 group_by = ''
673680 if self .group_by :
674- group_by = ' GROUP BY ' + ', ' .join (map (str , self .group_by ))
681+ group_by = ' GROUP BY ' + ', ' .join (
682+ map (str_or_ordinal , self .group_by ))
675683 having = ''
676684 if self .having :
677685 having = ' HAVING ' + str (self .having )
0 commit comments