Cumulative (running) sum with django orm and postgresql

前端 未结 5 873
你的背包
你的背包 2021-01-05 14:24

Is it possible to calculate the cumulative (running) sum using django\'s orm? Consider the following model:

class AModel(models.Model):
    a_number = models         


        
5条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 14:50

    From Dima Kudosh's answer and based on https://stackoverflow.com/a/5700744/2240489 I had to do the following: I removed the reference to PARTITION BY in the sql and replaced with ORDER BY resulting in.

    AModel.objects.annotate(
        cumsum=Func(
            Sum('a_number'), 
            template='%(expressions)s OVER (ORDER BY %(order_by)s)', 
            order_by="id"
        ) 
    ).values('id', 'cumsum').order_by('id', 'cumsum')
    

    This gives the following sql:

    SELECT "amodel"."id",
    SUM("amodel"."a_number") 
    OVER (ORDER BY id) AS "cumsum" 
    FROM "amodel" 
    GROUP BY "amodel"."id" 
    ORDER BY "amodel"."id" ASC, "cumsum" ASC
    

    Dima Kudosh's answer was not summing the results but the above does.

提交回复
热议问题