Forum Discussion

planc7's avatar
planc7
Icon for Helper I rankHelper I
2 years ago
Solved

Cumulative total that reset when is negative

Hi everyone, I'm opening this thread because the following doesn't give me the answer  https://community.fabric.microsoft.com/t5/DAX-Commands-and-Tips/Cumulative-Total-with-Reset-on-Negative-amount...
  • Anonymous's avatar
    Anonymous
    2 years ago

    Hi planc7 

     

    You can try using the following method in PowerQuery.

    let
      Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("TY/LDcAgDEN34QxSyKeUWRD7r9G4qmqO71mJk7WKipp5qSXKrh9G4vWjS6ITkXbiwKyQ7+Rmg2JCuP4isK91FkSHiEmhZ6MLciXqOz8pDBcdjHfyib0f", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Week = _t, Delta = _t]),
      #"Changed Type" = Table.TransformColumnTypes(
        Source,
        {{"Week", Int64.Type}, {"Delta", Int64.Type}}
      ),
      FX = (values as list) as list =>
        let
          GRTList = List.Generate(
            () => [GRT = values{0}, i = 0],
            each [i] < List.Count(values),
            each 
                let
                    nextGRT = if [GRT] > 0 then [GRT] + values{[i] + 1} else values{[i] + 1}
                in
                    [GRT = nextGRT, i = [i] + 1],
            each [GRT]
          )
        in
          GRTList,
      weeklist = List.Buffer(#"Changed Type"[Week]),
      deltalist = List.Buffer(#"Changed Type"[Delta]),
      result = Table.FromColumns(
        {Source[Week], Source[Delta], List.Transform(FX(deltalist), each if _ < 0 then 0 else _)},
        {"Week", "Delta", "Output"}
      ),
        #"Changed Type1" = Table.TransformColumnTypes(result,{{"Week", Int64.Type}, {"Delta", Int64.Type}, {"Output", Int64.Type}})
    in
      #"Changed Type1"

     

    Output:

     

    Best Regards,
    Yulia Xu

     

    If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.