0

I'm new to PowerPivot and DAX. I've followed some on-line tutorials. Now I have a small problem that I can't solve. I have the following data:

Date Instrument Value 2016-07-27 A 100 2016-07-27 B 98 2016-07-26 A 102 2016-07-25 B 99

For each date I would like to calculate the difference (Profit/Loss) in Value between most recent date and second most recent date. For the data above it would be the following:

Date Instrument Value Profit/Loss 2016-07-27 A 102 2 ([Val. inst. A 2016-07-27]-[Val. inst. A 2016-07-26]) 2016-07-27 B 98 -1 ([Val. inst. B 2016-07-27]-[Val. inst. B 2016-07-25]) 2016-07-26 A 100 2016-07-25 B 99

I have tried with DAX to find the second largest date using =EARLIER([Date])but haven't managed to get it to work. With the second largest date I would maybe be able to find the Value corresponding to that date. Any suggestions how this could be solved?

g3blv
  • 3,877
  • 7
  • 38
  • 51

1 Answers1

0

In the end I came up with a solution in three steps (the steps can be combined into one step). First I rank all the dates, with the most recent being 1 and the second most recent being 2. After that I retrieve the Value for the second most recent day for each row. Finally I calculate the difference between the Values current row and the Value for the second most recent day compared to that row's date.

To rank the dates I used the following:

=RANKX(FILTER(ALL(table);EARLIER([Instrument])=[Instrument]);[Date];;FALSE())

Explanation to what I think the DAX formula is doing. RANKX works by taking a table and then rank the values in a column in that table. Above I've used a filtered table as the table. The filtered table creates a new table for each row containing only the same instrument as the instrument for that particular row. For the first row, the filtered table would look like below.

Date Instrument Value 2016-07-27 A 100 2016-07-26 A 102

The dates in that filtered table is then ranked.

Date Instrument Value Rank 2016-07-27 A 100 1 2016-07-26 A 102 2

Using the Rank I then pull out the second most recent dates Value for each row based on the current row's Rank-1.

Value second most recent date = CALCULATE(MAX([Value]);FILTER(table;EARLIER([Instrument])=[Instrument] && [Date Rank]= EARLIER([Date Rank]))

Finally I calculate the difference:

PnL = [Value] - [Value second most recent date]

I'm not sure what EARLIER is doing but I think it is some sort of iterative process.

g3blv
  • 3,877
  • 7
  • 38
  • 51