简体   繁体   English

Django 查询以获取每个月的最佳表现者

[英]Django query to fetch top performers for each month

I need to fetch the top performer for each month, here is the below MySql query which gives me the correct output.我需要获取每个月的最佳表现者,这是下面的 MySql 查询,它为我提供了正确的输出。

select id,Name,totalPoints, createdDateTime 
from userdetail
where app=4 and totalPoints in ( select 
max(totalPoints) 
FROM userdetail
where app=4 
group by  month(createdDateTime), year(createdDateTime))
order by totalPoints desc

I am new to Django ORM.我是 Django ORM 的新手。 I am not able to write an equivalent Django query which does the task.我无法编写完成任务的等效 Django 查询。 I have been struggling with this logic for 2 days.我已经为这个逻辑苦苦挣扎了 2 天。 Any help would be highly appreciated.任何帮助将不胜感激。

While the GROUP BY clause in a subquery is slightly difficult to express with the ORM because aggregate() operations don't emit querysets, a similar effect can be achieved with a Window function:虽然子查询中的GROUP BY子句用 ORM 表达有点困难,因为aggregate()操作不发出查询集,但使用Window函数可以实现类似的效果:

UserDetail.objects.filter(total_points__in=UserDetail.objects.annotate(max_points=Window(
        expression=Max('total_points'),
        partition_by=[Trunc('created_datetime', 'month')]
    )).values('max_points')
)

In general, this sort of pattern is implemented with Subquery expressions .一般来说,这种模式是用Subquery表达式实现的。 In this case, I've implicitly used a subquery by passing a queryset to an __in predicate.在这种情况下,我通过将查询集传递给__in谓词来隐式使用子查询。

The Django documentation's notes on using aggregates within subqueries is are also relevant to this sort of query, since you want to use the results of an aggregate in a subquery (which I've avoided by using a window function). Django 文档关于在子查询中使用聚合的注释也与此类查询相关,因为您希望在子查询中使用聚合的结果(我已通过使用窗口函数避免了这种情况)。


However, I believe your query may not correctly capture what you want to do: as written it could return rows for users who weren't the best in a given month but did have the same score as another user who was the best in any month.但是,我相信您的查询可能无法正确捕获您想要执行的操作:如所写,它可能会返回给定月份中不是最好的用户的行,但与任何月份中最好的另一个用户的得分相同.

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

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