summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/ext/selectresults.py
diff options
context:
space:
mode:
authorMike Bayer <mike_mp@zzzcomputing.com>2006-08-11 21:43:55 +0000
committerMike Bayer <mike_mp@zzzcomputing.com>2006-08-11 21:43:55 +0000
commitc48727aeed66ae94d66b79790e841223c45f1a51 (patch)
treecb907fb8261e697058e6562479b23e1705def2a3 /lib/sqlalchemy/ext/selectresults.py
parent4488b655458b07ef060af5e5995b480d350d0bc9 (diff)
downloadsqlalchemy-c48727aeed66ae94d66b79790e841223c45f1a51.tar.gz
SelectResults will use a subselect, when calling an aggregate (i.e.
max, min, etc.) on a SelectResults that has an ORDER BY clause [ticket:252]
Diffstat (limited to 'lib/sqlalchemy/ext/selectresults.py')
-rw-r--r--lib/sqlalchemy/ext/selectresults.py22
1 files changed, 17 insertions, 5 deletions
diff --git a/lib/sqlalchemy/ext/selectresults.py b/lib/sqlalchemy/ext/selectresults.py
index 2ad52c8f0..79d56ec67 100644
--- a/lib/sqlalchemy/ext/selectresults.py
+++ b/lib/sqlalchemy/ext/selectresults.py
@@ -29,22 +29,34 @@ class SelectResults(object):
def count(self):
"""executes the SQL count() function against the SelectResults criterion."""
return self._query.count(self._clause)
-
+
+ def _col_aggregate(self, col, func):
+ """executes func() function against the given column
+
+ For performance, only use subselect if order_by attribute is set.
+
+ """
+ if self._ops.get('order_by'):
+ s1 = sql.select([col], self._clause, **self._ops).alias('u')
+ return sql.select([func(s1.corresponding_column(col))]).scalar()
+ else:
+ return sql.select([func(col)], self._clause, **self._ops).scalar()
+
def min(self, col):
"""executes the SQL min() function against the given column"""
- return sql.select([sql.func.min(col)], self._clause, **self._ops).scalar()
+ return self._col_aggregate(col, sql.func.min)
def max(self, col):
"""executes the SQL max() function against the given column"""
- return sql.select([sql.func.max(col)], self._clause, **self._ops).scalar()
+ return self._col_aggregate(col, sql.func.max)
def sum(self, col):
"""executes the SQL sum() function against the given column"""
- return sql.select([sql.func.sum(col)], self._clause, **self._ops).scalar()
+ return self._col_aggregate(col, sql.func.sum)
def avg(self, col):
"""executes the SQL avg() function against the given column"""
- return sql.select([sql.func.avg(col)], self._clause, **self._ops).scalar()
+ return self._col_aggregate(col, sql.func.avg)
def clone(self):
"""creates a copy of this SelectResults."""