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

Viewed 76117

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

From SQLAlchemy docs, for sum method, we need to use functions.sum(). As we can see:

from sqlalchemy.sql import functions

result = 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 ...
Related