Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)     #... 
like image 388
Andrew_1510 Avatar asked Aug 06 '12 15:08

Andrew_1510


People also ask

How do I sum a column in SQLAlchemy?

We first extract the average value of the percentage column using SQLalchemy's `func. avg()` function. Then we use the `func. sum()` function to get the sum of the values in the percentage column.

How many components are present in SQLAlchemy?

SQLAlchemy consists of two distinct components, known as the Core and the ORM.

What is subquery in SQLAlchemy?

The grouping is done with the group_by() query method, which takes the column to use for the grouping as an argument, same as the GROUP BY counterpart in SQL. The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.

What are generic functions in SQL?

A generic function is a pre-established Function class that is instantiated automatically when called by name from the func attribute. Note that calling any name from func has the effect that a new Function instance is created automatically, given that name.


1 Answers

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 
like image 169
van Avatar answered Oct 19 '22 15:10

van