The problem with specifying non-grouped and non-aggregate fields in group by
selects is that engine has no way of knowing which record's field it should return in this case. Is it first? Is it last? There is usually no record that naturally corresponds to aggregated result (min
and max
are exceptions).
However, there is a workaround: make the required field aggregated as well. In posgres, this should work:
SELECT cname, (array_agg(wmname ORDER BY avg DESC))[1], MAX(avg)
FROM makerar GROUP BY cname;
Note that this creates an array of all wnames, ordered by avg, and returns the first element (arrays in postgres are 1-based).