[Django]-Cumulative (running) sum of field Django and MySQL

0👍

Edit for the correct answer:

Tip.objects.values(
    "prediction__fixture__date__date"
).annotate(
    cum_pl=Window(
        expression=Sum('pl'),
        order_by=ExtractDay('prediction__fixture__date__date').desc()
    )
).distinct("prediction__fixture__date__date")

I gives the query

SELECT
  DISTINCT ON (
    ("transactions_fixture"."date" AT TIME ZONE 'UTC') :: date
  ) ("transactions_fixture"."date" AT TIME ZONE 'UTC') :: date,
  SUM("transactions_tip"."pl") OVER (
    ORDER BY
      EXTRACT(
        'day'
        FROM
          "transactions_fixture"."date" AT TIME ZONE 'UTC'
      ) DESC
  ) AS "cum_pl"
FROM
  "transactions_tip"
  INNER JOIN "transactions_prediction" ON (
    "transactions_tip"."prediction_id" = "transactions_prediction"."id"
  )
  LEFT OUTER JOIN "transactions_fixture" ON (
    "transactions_prediction"."fixture_id" = "transactions_fixture"."id"
  )

Just tested on a fiddle and worked fine, let me know if it doesn’t.

-2👍

try this.

Tip.objects.values(
    "prediction__fixture__date__date"
).annotate(
    cum_pl=Sum('pl', distinct=True)
).order_by("prediction__fixture__date__date")

Leave a comment