Sub topic 3
Table Filters and Context Transition in DAX
Assume you know basic DAX measures, calculated columns, and star-schema relationships. In this chapter, you will see how CALCULATE handles table filters, row context, and relationships.
Table filters and `FILTER`
A table filter argument supplies rows that CALCULATE uses to modify the filter context. FILTER evaluates a condition for each row in a table.
High Quantity Sales =
CALCULATE (
[Total Sales],
FILTER ( Sales, Sales[Quantity] > 2 )
)This keeps the current filters on Sales and adds the condition that quantity must be greater than two. Use FILTER when the condition needs an expression or multiple columns. For a simple column comparison, a Boolean filter is usually clearer.
Context transition: row context to filter context
Row context means “the current row,” such as a row being processed by AVERAGEX. Row context alone does not filter a measure. Referencing a measure inside an iterator triggers an implicit CALCULATE, which converts the current row into filters.
Average Sales per Customer =
AVERAGEX ( Customer, [Total Sales] )For each customer row, the customer key becomes a filter. [Total Sales] then evaluates for that customer.
Evaluation order in `CALCULATE`
CALCULATE evaluates its filter arguments independently in the original filter context. It then performs context transition, applies relationship and filter modifiers, and applies the resulting filters. This order matters when several arguments affect the same columns or relationships.
Switching relationships with `USERELATIONSHIP`
A model can contain multiple relationships between two tables, with only one active by default. USERELATIONSHIP activates an inactive relationship for one calculation.
Sales by Ship Date =
CALCULATE (
[Total Sales],
USERELATIONSHIP ( Sales[ShipDate], 'Date'[Date] )
)The relationship returns to its original state after the measure finishes.
Common pitfalls and debugging
- A Boolean filter such as
'Product'[Color] = "Red"replaces an existing filter on that column. - A variable stores its value when it is defined. A later
CALCULATEcannot recalculate that stored value. - Check each filter argument separately in temporary measures.
- Inspect the active relationships and confirm that filter direction matches the model design.
Exercise
Why can CALCULATE ( t, 'Product'[Color] = "Red" ) fail to change t when t was defined as VAR t = [Total Sales]?
Show answer
The variable was evaluated before CALCULATE changed the filter context, so t already contains the original result.