栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

计算在Django ORM中按查询分组的带注释字段的总和最大值?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

计算在Django ORM中按查询分组的带注释字段的总和最大值?

您无法进行汇总的汇总

Max(Sum())
,无论您是否使用ORM,它在SQL中都是无效的。相反,您必须将表自身联接起来才能找到最大值。您可以使用子查询来执行此操作。下面的代码对我来说似乎很正确,但是请记住,我没有什么可以运行的,因此它可能并不完美。

from django.db.models import Subquery, OuterRefannotation = {    'AcSum': Sum('intensity')}# The basic query is on Relation grouped by A and Category, annotated# with the Sum of intensityquery = Relation.objects.values('a', 'b__category').annotate(**annotation)# The subquery is joined to the outerquery on the Categorysub_filter = Q(b__category=OuterRef('b__category'))# The subquery is grouped by A and Category and annotated with the Sum# of intensity, which is then ordered descending so that when a LIMIT 1# is applied, you get the Max.subquery = Relation.objects.filter(sub_filter).values('a', 'b__category').annotate(**annotation).order_by('-AcSum').values('AcSum')[:1]query = query.annotate(max_intensity=Subquery(subquery))

这应该生成如下的SQL:

SELECt a_id, category_id,       (SELECT SUM(U0.intensity) AS AcSum        FROM RELATION U0        JOIN B U1 on U0.b_id = U1.id        WHERe U1.category_id = B.category_id        GROUP BY U0.a_id, U1.category_id        ORDER BY SUM(U0.intensity) DESC        LIMIT 1       ) AS max_intensityFROM RelationJOIN B on Relation.b_id = B.idGROUP BY Relation.a_id, B.category_id

通过使用特定于后端的功能(例如array_agg(Postgres)或GroupConcat(MySQL))收集在外部查询中分组在一起的Relation.id,在子查询中消除联接可能会更有效。但是我不知道您正在使用什么后端。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/623553.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号