“greatest-n-per-group” query in Django 2.0?

三世轮回 提交于 2019-12-23 15:39:06

问题


Basically, I want to do this but with django 2.0.

If I try:

Purchases.objects.filter(.....).annotate(my_max=Window( expression=Max('field_of_interest'), partition_by=F('customer') ) )

I get back all the rows but with the my_max property added to each record.


回答1:


If you are using PostgreSQL:

Purchases.objects.filter(.....).order_by(
    'customer', '-field_of_interest'
).distinct('customer')

or with Window expression

Purchases.objects.filter(.....).annotate(my_max=Window(
    expression=Max('field_of_interest'),
    partition_by=F('customer')
    )
).filter(my_max=F('field_of_interest'))

but latter can yield multiple rows per customer if they have the same field_of_interest

Another Window, with single row per customer

Purchases.objects.filter(.....).annotate(row_number=Window(
        expression=RowNumber(),
        partition_by=F('customer'),
        order_by=F('field_of_interest').desc()
        )
    ).filter(row_number=1)


来源:https://stackoverflow.com/questions/51140307/greatest-n-per-group-query-in-django-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!