Forum Discussion
SJHardeman
3 years agoFrequent Visitor
CALCULATE / FILTER DAX code issue
Hi, I have been trying to use the below DAX code to do the following: (1) take the Data table, sum the FTE column filtered whereby the date in the Period column equals a measure [Latest month] ...
- 3 years ago
Hi SJHardeman
First, here's a bit of an explanation of what's going on:
- When a measure such as [Latest month] is invoked, it is automatically surrounded by a hidden CALCULATE (...).
- The FILTER function is an iterator which evaluates the condition in the 2nd argument in the row context of each row the table specified in the 1st argument.
- Within a row context, CALCULATE triggers context transition, which transforms the row context into an equivalent filter context. All columns within the "current row" become filters.
- Applying this to your measure: [Latest month] and [First month] are evaluated within a filter context corresponding to each row of the Data table. This means the conditions [Latest month]='Data'[Period] and [First month] = 'Data'[Period] are always TRUE.
Here is a good article on this overall topic:
https://www.sqlbi.com/articles/understanding-context-transition-in-dax/
A couple of side points:
- FIRSTDATE and LASTDATE return tables (1 row x 1 column), and are typically used as SetFilter arguments within CALCULATE. If you just want to return a scalar value, you can use MIN or MAX.
- For any date-based filtering, it is best to create a separate 'Date' dimension. However, I won't worry about this for the purpose of this question.
You can fix this a few ways. I would personally recommend creating these measures:
FTE Sum = SUM ( data[FTE] )FTE First Month = CALCULATE( [FTE Sum], FIRSTDATE ( data[Period] ) )FTE Last Month = CALCULATE( [FTE Sum], LASTDATE ( data[Period] ) )FTE_change = [FTE Last Month] - [FTE First Month]Does this work for you?
Regards
SJHardeman
3 years agoFrequent Visitor
Hi Owen, thanks for explaining this so clearly. The solution worked. Thanks, Sam
SJHardeman
3 years agoFrequent Visitor
Hi OwenAuger, how would I modify the code if I wanted to also have another measure which calculated FTE_change for [FTE Last Month] - [FTE Penultimate Month]. Using the below
results in an error
FTE Penultimate Month = CALCULATE([FTE Sum], EDATE(LASTDATE(Staff_Collated_HQ_WFPT[Period]),-1))