Skip to content
Advertisement

sqlalchemy simple example of `sum`, `average`, `min`, `max`

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)
    #...

Advertisement

Answer

See SQL Expression Language Tutorial for the usage. The code below shows the usage:

from sqlalchemy.sql import func
qry = 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
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement