Sub topic 6
Iterators: SUMX, AVERAGEX, and FILTER
This chapter assumes you can write simple measures with SUM and COUNTROWS, and that you know a measure is evaluated in a filter context while a calculated column is evaluated row by row. It also assumes you understand one-to-many relationships between a fact table (Sales) and dimension tables (Product, Customer). The earlier chapters introduced filter context and row context. Here you use them together through iterator functions.
What an iterator does
An iterator is a DAX function that takes a table, visits each row of that table, and evaluates an expression once per row. Each visit happens inside a row context, so the expression can read the columns of the current row directly. The iterator then combines the per-row results.
Most iterator names end in X: SUMX, AVERAGEX, MINX, MAXX, COUNTX, and RANKX. FILTER also visits every row of a table, but it returns a table instead of a number.
Every iterator takes two kinds of input:
- A table argument, which says which rows to visit.
- An expression argument, which is evaluated once for each of those rows.
These two arguments run in different contexts. The table argument is evaluated once, in the filter context of the caller. The expression is evaluated many times, each time inside a new row context created by the iterator. This difference explains most iterator behavior.
SUMX: sum of a per-row expression
Suppose the Sales table has Quantity and Unit Price columns. Revenue is quantity times price for each line, summed over all lines. A plain SUM cannot do this, because SUM adds one column and cannot multiply two columns first.
Sales Amount =
SUMX ( Sales, Sales[Quantity] * Sales[Unit Price] )Take three rows in the current filter context:
| Row | Quantity | Unit Price | Row result |
|---|---|---|---|
| 1 | 2 | 10 | 20 |
| 2 | 3 | 5 | 15 |
| 3 | 1 | 20 | 20 |
SUMX returns 20 + 15 + 20 = 55. The filter context decides which Sales rows are in the table argument. If a slicer selects one product, only the rows for that product are iterated. The measure itself does not change.
SUM is a shortcut. SUM ( Sales[Quantity] ) is equivalent to SUMX ( Sales, Sales[Quantity] ). Using SUMX for a single column gives no benefit, but it shows that SUM is also an iteration.
Compare these two measures:
Wrong Amount =
SUM ( Sales[Quantity] ) * AVERAGE ( Sales[Unit Price] )For the three rows above, this returns 6 × 11.67 = 70, not 55. Multiplying aggregates is not the same as aggregating products. Use an iterator whenever the formula must be applied before the aggregation.
Reading related columns inside an iterator
The row context lets you follow a relationship toward the one side with RELATED. Assume Product has a Unit Cost column and a one-to-many relationship to Sales:
Total Cost =
SUMX ( Sales, Sales[Quantity] * RELATED ( Product[Unit Cost] ) )For each Sales row, RELATED finds the matching Product row and returns its Unit Cost. This works because the iterated table (Sales) is on the many side. Going the other direction, from Product to Sales, needs RELATEDTABLE or context transition, which a later chapter covers.
AVERAGEX: average of a per-row expression
AVERAGEX evaluates the expression for each row and then averages the results. The simplest use is an average of a row-level calculation:
Average Line Amount =
AVERAGEX ( Sales, Sales[Quantity] * Sales[Unit Price] )For the three rows above, the result is 55 / 3, which is about 18.33.
The more useful pattern iterates over a dimension and evaluates a measure for each member. This answers questions such as "what is the average sales per customer?"
Average Sales per Customer =
AVERAGEX ( Customer, [Sales Amount] )Here the iterator opens a row context on each Customer row. The reference to [Sales Amount] inside the expression makes DAX turn that row into a filter on the Customer table, so each customer gets their own sales total. This conversion is called context transition. It has its own chapters, so for now accept that the measure reference inside the iterator is what makes each row produce a different value.
Blanks and empty tables
AVERAGEX skips rows where the expression returns BLANK. A customer with no sales rows gets a blank [Sales Amount], so that customer is not counted in the average. The result is the average over customers who bought something, not over all customers.
If you want customers without sales to count as zero, make the expression return zero explicitly:
Average Sales per Customer Incl Zero =
AVERAGEX ( Customer, [Sales Amount] + 0 )Adding zero turns the blank into 0, so every customer is counted. Pick the version that matches the question you are asked. Mixing them up is a common source of a number that is "almost right".
If the table argument is empty, or every expression result is blank, AVERAGEX and SUMX return BLANK, not zero. A report visual hides rows where the measure is blank. That is often what you want, but it matters when you build a chain of measures.
Iterating over a column instead of a table
The table argument can be any table expression, not only a physical table. Iterating over distinct values of a column is cheaper than iterating over a large table when you only need the column's values:
Average Sales per Category =
AVERAGEX ( VALUES ( Product[Category] ), [Sales Amount] )VALUES returns the distinct categories visible in the current filter context. The iteration then runs once per category and not once per product.
FILTER: an iterator that returns a table
FILTER takes a table and a true/false condition. It evaluates the condition for each row and returns a table that contains only the rows where the condition is true.
Products Over 1000 =
COUNTROWS (
FILTER ( Product, [Sales Amount] > 1000 )
)FILTER visits each Product row. For each one, [Sales Amount] is evaluated for that product, again through context transition. If the result exceeds 1000, the row is kept. COUNTROWS then counts the surviving rows.
Because FILTER returns a table, it cannot be the final result of a measure by itself. A measure must return a single value. Wrap FILTER in a function that accepts a table, such as COUNTROWS, SUMX, or the filter argument of CALCULATE.
Sales of Large Lines =
CALCULATE (
[Sales Amount],
FILTER ( Sales, Sales[Quantity] * Sales[Unit Price] > 100 )
)The condition here compares a row-level expression against 100. A simple column filter such as Sales[Quantity] > 2 cannot express it, because it compares a computed value. This is a legitimate use of FILTER over a fact table.
Which filter context does FILTER see?
The table argument of FILTER is evaluated in the filter context of the caller. In the first example, FILTER iterates the Product rows that are visible in the current report. If the visual shows only the Bikes category, only bike products are tested.
If you need to ignore the existing filters, replace the table with one that removes them:
Products Over 1000 All Categories =
COUNTROWS (
FILTER ( ALL ( Product ), [Sales Amount] > 1000 )
)ALL returns every Product row regardless of the current filter context on Product. The count then covers the whole catalog. Note that [Sales Amount] is still evaluated in the surrounding filter context plus the transition filter for each product. Other filters, such as a Date slicer, still apply.
Context inside the expression
Inside an iterator, the expression has two contexts at the same time:
- The filter context inherited from outside the iterator. A slicer on Date still applies.
- The row context created by the iterator. It exposes the columns of the current row.
A row context does not filter other tables. Consider a calculated column on Product:
-- Calculated column in the Product table
Sales Without Transition =
SUMX ( Sales, Sales[Quantity] * Sales[Unit Price] )The calculated column runs in a row context on Product, but the row context does not filter Sales. SUMX therefore iterates all Sales rows, and every product shows the same grand total. Changing the column to = [Sales Amount] would add the implicit CALCULATE that makes each product show its own sales. The next chapters explain why.
Common mistakes and edge cases
- Multiplying aggregates.
SUM(a) * SUM(b)is notSUMX(t, a * b). Use the iterator when the per-row formula comes first. - Iterating a big fact table when a column filter works.
FILTER ( Sales, Sales[Color] = "Red" )scans every Sales row. A Boolean filter argument in CALCULATE, such asProduct[Color] = "Red", is clearer and lets the engine optimize. - Blanks hiding customers. AVERAGEX skips blank results. Decide whether missing means zero or means excluded.
- Using FILTER as a measure result. A table cannot be returned from a measure. Wrap it in COUNTROWS, SUMX, or CALCULATE.
- Measure references in large iterations. Each measure reference inside an iterator triggers a context transition per row. Iterating millions of rows with a measure inside is slow. Iterate over a smaller table such as VALUES of a column, or move the arithmetic into the expression.
Summary of the three functions
| Function | Returns | Table argument | Expression argument |
|---|---|---|---|
| SUMX | A number | Rows to visit | Value to add per row |
| AVERAGEX | A number | Rows to visit | Value to average per row, blanks skipped |
| FILTER | A table | Rows to test | Condition that keeps or drops each row |
Exercise
A Customer table has 100 customers, and 80 of them have sales. The measure AVERAGEX ( Customer, [Sales Amount] ) returns 500. How would you change the measure so it divides the total by 100 customers, and why does the original result differ?
Show answer
The original measure averages over the 80 customers whose [Sales Amount] is not blank, because AVERAGEX skips blank results. To count all 100 customers, return zero for the missing ones: AVERAGEX ( Customer, [Sales Amount] + 0 ). The total is then divided by 100, so the result is lower than 500 (400 if the total is 40,000).
Exercise
Why does Sales of Large Lines use FILTER over Sales rather than a Boolean filter such as Sales[Quantity] > 100? Write a measure that counts Sales rows where the line amount exceeds 100.
Show answer
The condition compares the product of two columns, which is a row-level calculation, and a simple Boolean filter on one column cannot express it. FILTER evaluates the expression for each row. One correct measure is COUNTROWS ( FILTER ( Sales, Sales[Quantity] * Sales[Unit Price] > 100 ) ).