Aggregate functions in order by section

The aggregate functions can be used inside the Query.order_by() function. Here is an example:

  1. select((s.group, avg(s.gpa)) for s in Student) \
  2. .order_by(lambda s: desc(avg(s.gpa)))

Another way of ordering by an aggregated value is specifying the position number inside the Query.order_by() method:

  1. select((s.group, avg(s.gpa)) for s in Student).order_by(-2)