[英]How to use avg and sum in SQLAlchemy query
我試圖從我的數據集中返回一個總計/平均值行,其中包含某些字段的 SUM 和其他字段的 AVG。
我可以通過以下方式在 SQL 中執行此操作:
SELECT SUM(field1) as SumFld, AVG(field2) as AvgFld
FROM Rating WHERE url=[url_string]
我將其轉換為 SQLAlchemy 的嘗試如下:
totals = Rating.query(func.avg(Rating.field2)).filter(Rating.url==url_string.netloc)
但這是錯誤的:
TypeError: 'BaseQuery' object is not callable
你應該使用類似的東西:
from sqlalchemy.sql import func
session.query(func.avg(Rating.field2).label('average')).filter(Rating.url==url_string.netloc)
你不能在這里使用MyObject.query
,因為 SqlAlchemy 試圖找到一個字段來放置avg
函數的結果,但它失敗了。
你不能在這里使用 MyObject.query,因為 SqlAlchemy 試圖找到一個字段來放置 avg 函數的結果,但它失敗了。
這不完全正確。 func.avg(Rating.field2).label('average')
返回一個Column
對象(准確地說是與它相同的類型對象)。 因此,您可以將它與查詢對象的with_entities
方法一起使用。
這是您為示例執行的操作:
Rating.query.with_entities(func.avg(Rating.field2).label('average')).filter(Rating.url == url_string.netloc)
attention = Attention_scores.query
.with_entities(func.avg(Attention_scores.score))
.filter(classroom_number == classroom_number)
.all()
我像這樣嘗試過,它給出了正確的平均值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.