python - 我可以使用 SQLAlchemy 使用聚合表达式吗?

标签 python postgresql sqlalchemy aggregate-functions

PostgreSQL 有 aggregate expressions ,例如count(*) FILTER(WHERE state = 'success')。如何使用 SQLAlchemy 生成此类表达式?

最佳答案

假设我有一个带有 bool 字段active 的模型Machine,并且想通过active = true 过滤计数

>

使用func.count(...).filter(...)

from models import db, Machine
from sqlalchemy.sql import func

query = db.session.query(
    func.count(Machine.id).filter(Machine.active == True)
    .label('active_machines')
)

我们可以看看生成的 SQL 查询:

>>> print(query)
SELECT count(machine.id) FILTER (WHERE machine.active = true) AS active_machines 
FROM machine

这对于其他聚合函数应该同样有效,例如 func.avgfunc.sum

使用 funcfilter(count(...), filter) 的更长语法

func.count(Machine.id).filter(Machine.active == True) 是以下内容的简写:

from sqlalchemy import funcfilter

funcfilter(func.count(Machine.id), Machine.active == True)

关于python - 我可以使用 SQLAlchemy 使用聚合表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47324538/

相关文章:

Python 解码维基百科文章失败?

c# - 如何从VS中的数据库中的数据绘制图形

postgresql - Postgres- "ERROR: generation expression is not immutable"为什么我的表达式不是一成不变的?

sql - rails : query the existence of a join table's child

python - SQLAlchemy 中的嵌套连接

python - Flask-reSTLess 使用 unicode 字段创建模型

php - 需要帮助将我漂亮的 soup (Python) 代码转换为 PHP

python - 如何请求输入来切片 pandas 数据框

python - Pygame : Is color readable from a class variable in function pygame. 绘制.矩形?

python - SQLAlchemy with_for_update 读取陈旧数据