@@ -678,6 +678,10 @@ func inferColNameFromExpr(
678678 rv .DecoratedColumn = fmt .Sprintf (`%s%s` , rv .DecoratedColumn , constants .PostgresJSONCastSuffix )
679679 }
680680 }
681+ // Propagate aggregate status from arguments
682+ if rv .IsAggregateExpr {
683+ retVal .IsAggregateExpr = true
684+ }
681685 exprsDecorated = append (exprsDecorated , rv .DecoratedColumn )
682686 }
683687 }
@@ -799,6 +803,23 @@ func inferColNameFromExpr(
799803 return retVal , nil
800804 }
801805 }
806+ case * sqlparser.BinaryExpr :
807+ // Binary expressions (arithmetic, etc.) are computed expressions
808+ decoratedColumn := astformat .String (expr , formatter )
809+ retVal .DecoratedColumn = getDecoratedColRendition (decoratedColumn , alias )
810+ // Check if either operand contains aggregate/window functions
811+ lhsRetval , _ := inferColNameFromExpr (expr .Left , formatter , "" )
812+ rhsRetval , _ := inferColNameFromExpr (expr .Right , formatter , "" )
813+ // If either side is an aggregate expression, the whole binary expr is computed
814+ if lhsRetval .IsAggregateExpr || rhsRetval .IsAggregateExpr {
815+ retVal .IsAggregateExpr = true
816+ }
817+ // Try to get a name from either operand for reference
818+ if lhsRetval .Name != "" {
819+ retVal .Name = lhsRetval .Name
820+ } else if rhsRetval .Name != "" {
821+ retVal .Name = rhsRetval .Name
822+ }
802823 default :
803824 decoratedColumn := astformat .String (expr , formatter )
804825 retVal .DecoratedColumn = getDecoratedColRendition (decoratedColumn , alias )
0 commit comments