简体   繁体   English

`sum`、`average`、`min`、`max`的sqlalchemy简单示例

[英]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).对于sqlalchemy ,谁能给一列简单的SQL函数如sumaverageminmax的例子(下面以score为例)。

As for this mapper:至于这个映射器:

class Score(Base):
    #...
    name = Column(String)
    score= Column(Integer)
    #...

See SQL Expression Language Tutorial for the usage. 有关用法,请参阅SQL表达式语言教程 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

From SQLAlchemy docs , for sum method, we need to use functions.sum() .SQLAlchemy docs ,对于sum方法,我们需要使用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:这将产生一个 sql,如:

SELECT sum(public.model.value_a + public.model.value_b) AS sum_1 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM