@@ -115,18 +115,6 @@ transformAggregateCall(ParseState *pstate, Aggref *agg,
115115 int save_next_resno ;
116116 ListCell * lc ;
117117
118- /*
119- * Before separating the args into direct and aggregated args, make a list
120- * of their data type OIDs for use later.
121- */
122- foreach (lc , args )
123- {
124- Expr * arg = (Expr * ) lfirst (lc );
125-
126- argtypes = lappend_oid (argtypes , exprType ((Node * ) arg ));
127- }
128- agg -> aggargtypes = argtypes ;
129-
130118 if (AGGKIND_IS_ORDERED_SET (agg -> aggkind ))
131119 {
132120 /*
@@ -238,6 +226,29 @@ transformAggregateCall(ParseState *pstate, Aggref *agg,
238226 agg -> aggorder = torder ;
239227 agg -> aggdistinct = tdistinct ;
240228
229+ /*
230+ * Now build the aggargtypes list with the type OIDs of the direct and
231+ * aggregated args, ignoring any resjunk entries that might have been
232+ * added by ORDER BY/DISTINCT processing. We can't do this earlier
233+ * because said processing can modify some args' data types, in particular
234+ * by resolving previously-unresolved "unknown" literals.
235+ */
236+ foreach (lc , agg -> aggdirectargs )
237+ {
238+ Expr * arg = (Expr * ) lfirst (lc );
239+
240+ argtypes = lappend_oid (argtypes , exprType ((Node * ) arg ));
241+ }
242+ foreach (lc , tlist )
243+ {
244+ TargetEntry * tle = (TargetEntry * ) lfirst (lc );
245+
246+ if (tle -> resjunk )
247+ continue ; /* ignore junk */
248+ argtypes = lappend_oid (argtypes , exprType ((Node * ) tle -> expr ));
249+ }
250+ agg -> aggargtypes = argtypes ;
251+
241252 check_agglevels_and_constraints (pstate , (Node * ) agg );
242253}
243254
0 commit comments