For sqlalchemy, Who can gently give simple examples of SQL
functions like sum
, average
, min
, max
, for a column (score
in the following as an example).
As for this mapper:
class Score(Base):#...name = Column(String)score= Column(Integer)#...
Best Answer
See SQL Expression Language Tutorial for the usage. The code below shows the usage:
from sqlalchemy.sql import funcqry = session.query(func.max(Score.score).label("max_score"), func.sum(Score.score).label("total_score"),)qry = qry.group_by(Score.name)for _res in qry.all():print _res
From SQLAlchemy docs, for sum
method, we need to use functions.sum()
. As we can see:
from sqlalchemy.sql import functionsresult = session.query(functions.sum(Model.value_a + Model.value_b)).scalar()
that will produce a sql like:
SELECT sum(public.model.value_a + public.model.value_b) AS sum_1 ...