如何在SQLAlchemy查询中使用平均和总和 [英] How to use avg and sum in SQLAlchemy query

查看:521
本文介绍了如何在SQLAlchemy查询中使用平均和总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数据集中返回总计/平均值行,其中包含某些字段的SUM和其他字段的AVG.

I'm trying to return a totals/averages row from my dataset which contains the SUM of certain fields and the AVG of others.

我可以通过以下方式在SQL中完成此操作:

I could do this in SQL via:

SELECT SUM(field1) as SumFld, AVG(field2) as AvgFld 
FROM Rating WHERE url=[url_string]

我将其转换为SQLAlchemy的尝试如下:

My attempt to translate this into SQLAlchemy is as follows:

totals = Rating.query(func.avg(Rating.field2)).filter(Rating.url==url_string.netloc)

但这是错误的:

TypeError: 'BaseQuery' object is not callable

推荐答案

您应使用类似以下内容的

You should use something like:

from sqlalchemy.sql import func
session.query(func.avg(Rating.field2).label('average')).filter(Rating.url==url_string.netloc)

您不能在这里使用MyObject.query,因为SqlAlchemy试图找到一个将avg函数结果放入的字段,但失败.

You cannot use MyObject.query here, because SqlAlchemy tries to find a field to put result of avg function to, and it fails.

这篇关于如何在SQLAlchemy查询中使用平均和总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆