aggregate methods fail on SelectResults instance with ordering

Issue #252 resolved
Former user created an issue

The SelectResults class has aggregate methods, min, max, sum, and avg which are implemented identically. They fail (on Postgres at least) when they are called on an instance that has order_by defined in the _ops attribute because ordering doesn't make sense (in SQL) for the result, which is the aggregate. Though in context, these methods do make sense as they do not have the same purpose as filter, but rather act on final results. They return a scalar rather than another SelectResults instance like filter. I propose that these methods are implemented differently when order_by is defined. They should call the aggregate on a subquery that contains the ordering so that the ordering doesn't interfere. If order_by is not defined, a normal select is performed. I've attached a patch for review.

I imagine that the subquery method does not perform as well and I thought about just leaving out _ops so that the select just looks like this:

sql.select([func(col)](func(col)), self._clause)

But I don't know if that's a safe assumption because something important to the results may be contained in _opts. The subselect is safe because it only goes into effect when the query would normally fail.

Comments (3)

  1. Log in to comment