Search code examples
for-looprecursionpowerbidaxcalculated-columns

DAX for populating column value based on previous row of same column


I am trying to replicate this Excel formula or for loop that calculates the current row value based on the previous row value of the same column.
When value = 1, Result = Rank * 1 Else, Result = Rank * previous Result

| Value | Rank | Result |
| ----- | ---- | ------ |
|   1   |   3  |   3    |
|   2   |   2  |   6    |
|   3   |   1  |   6    |

I already tried generating a series table to get the Value and Rank columns but I am unable to refer to the existing Result column to update the same. Is there a way to get this done using DAX for dynamic number of rows?


Solution

  • It can be done, but you need to get your mindset out of recursion. Notice that I did [Rank] even for [Value] equal 1, as [Rank] * [Value] in that case is equal [Rank] (value equals 1, right?).

    Result =
    IF (
        Table[Value] = 1,
        [Rank],
        [Rank] *
        PRODUCTX (
            FILTER ( Table, Table[Value] < EARLIER ( Table[Value] ) ),
            [Rank]
        )
    )
    

    enter image description here

    EDIT:

    The previous one was unneccessarily complex:

    Result =
    CALCULATE (
        PRODUCT ( [Rank] ),
        FILTER ( Table, [Value] <= EARLIER ( [Value] ) )
    )