Sub topic 3
Removing and Preserving Filters in DAX
Assume you know tables, columns, one-to-many relationships, measures, and basic aggregations. In this chapter, Product filters the many-side Sales table through a relationship.
Removing and preserving filters
ALL removes filters from a table or column and can also return the resulting table. REMOVEFILTERS clears filters but communicates the intent more clearly when used as a CALCULATE argument. KEEPFILTERS intersects a new filter with the existing filter instead of replacing it.
All Product Sales =
CALCULATE ( [Sales Amount], REMOVEFILTERS ( Product ) )
Red Sales =
CALCULATE ( [Sales Amount], Product[Color] = "Red" )
Red Sales Within Selection =
CALCULATE (
[Sales Amount],
KEEPFILTERS ( Product[Color] = "Red" )
)If a visual already selects blue products, Red Sales replaces that color filter and returns red sales. Red Sales Within Selection keeps the existing selection, so the result is empty when red and blue do not overlap.
Measures and context transition
A measure reference behaves as if it were wrapped in CALCULATE. This matters inside an iterator or calculated column. CALCULATE converts the current row into filters. This conversion is called context transition.
Average Sales per Customer =
AVERAGEX ( Customer, [Sales Amount] )AVERAGEX creates a row context for each customer. The measure reference triggers context transition, so each customer’s row filters Sales before [Sales Amount] is evaluated.
Pitfalls and nested rows
Context transition needs a reliable key. Duplicate dimension keys can filter several rows unexpectedly. A missing relationship key may produce blank related values or no matching sales. Iterating a large table and evaluating a measure for every row can also be slow. Aggregate at a suitable grain when possible.
Nested iterators create multiple row contexts. Prefer variables over EARLIER, which is harder to read and easier to misuse.
Price Rank =
VAR CurrentPrice = Product[Unit Price]
RETURN
COUNTROWS (
FILTER ( Product, Product[Unit Price] > CurrentPrice )
) + 1The variable stores the outer product’s price before FILTER opens its inner row context.
Exercise
Which expression preserves a slicer’s existing color filter while adding red?
Show answer
CALCULATE ( [Sales Amount], KEEPFILTERS ( Product[Color] = "Red" ) ).