MSBA-261 · Lesson 8 of 12 · 22 min
Iterators and ranking
▶ Video coming soon A video version of this lesson is on the way.
The bookstore managers had a request that sounded simple: a ranked list of product categories by gross margin, with the median and spread of weekly margin for each, so they could see which categories were reliably profitable and which swung wildly. Gross margin had to be calculated line by line, because each sales line had its own price and cost. Ranking had to respond to whatever outlet and term the reader picked. Both needed a kind of DAX function Kwabena had used only once: the iterator. This lesson covers iterators, ranking with RANKX and the newer window functions, and the basic statistical functions the PL-300 exam expects.
Aggregators and iterators
Functions such as SUM and AVERAGE are aggregators: they take one column and summarize it in the current filter context. That is all they can do. SUM ( 'Outlet Sales'[Sales Amount] ) adds up a column that already exists.
Iterators are functions ending in X, such as SUMX, AVERAGEX, MINX, MAXX and COUNTX, plus functions like FILTER, RANKX and CONCATENATEX. An iterator takes a table and an expression. It steps through the table one row at a time, creating a row context for each row, evaluates the expression for that row, and then aggregates the results.
Gross Margin =
SUMX (
'Outlet Sales',
'Outlet Sales'[Quantity] * ( 'Outlet Sales'[Unit Price] - 'Outlet Sales'[Unit Cost] )
)
Gross Margin Rate = DIVIDE ( [Gross Margin], [Outlet Sales] )Without SUMX, Kwabena would have needed a calculated column for line margin and a SUM over it. That works, but it stores a column for every sales line, millions of values, while the iterator computes the same result at query time without storing anything. For simple arithmetic on columns of the same table, the engine evaluates SUMX efficiently, so this is usually the better choice. When the per-row value is also needed for slicing, such as a margin band, a column is still the right tool.
Iterating over a dimension
Iterators are most interesting when the table they iterate is not the fact table but a dimension, or a list of values. Then each row of the iteration has its own filter context through context transition, and the expression can be a measure.
Average Weekly Sales =
AVERAGEX ( VALUES ( 'Date'[Week Start] ), [Outlet Sales] )
Best Week Sales =
MAXX ( VALUES ( 'Date'[Week Start] ), [Outlet Sales] )VALUES ( 'Date'[Week Start] ) returns the distinct weeks visible in the current filter context. AVERAGEX steps through them, and for each week, the reference to [Outlet Sales] triggers context transition, so it is evaluated for that week only. The result is the average of weekly totals. That is a different number from AVERAGE ( 'Outlet Sales'[Sales Amount] ), which would be the average sales line. Deciding what you are averaging over is the main question in any average measure: the average per line, per receipt, per week or per outlet are all different numbers.
Iterators and performance
Iterators are powerful, and they can be slow when misused. A measure reference inside an iterator triggers context transition for every row of the iterated table. Iterating a dimension with a few hundred rows, such as weeks or categories, is fine. Iterating a fact table with millions of rows and calling a measure for each row can be very slow. As a rule, iterate the smallest table that answers the question, and use column arithmetic rather than measures inside iterators over large fact tables.
Basic statistical functions
The PL-300 study guide asks for basic statistical functions. DAX provides the familiar set, each with an aggregator form for a column and an iterator form for an expression over a table.
| Statistic | Column form | Iterator form | Bookstore use |
|---|---|---|---|
| Average | AVERAGE | AVERAGEX | Average weekly sales per category |
| Median | MEDIAN | MEDIANX | Typical weekly margin, less affected by one huge textbook week |
| Minimum and maximum | MIN, MAX | MINX, MAXX | Worst and best week |
| Standard deviation | STDEV.S, STDEV.P | STDEVX.S, STDEVX.P | How much weekly margin varies |
| Variance | VAR.S, VAR.P | VARX.S, VARX.P | Spread, used in some planning models |
| Percentile | PERCENTILE.INC, PERCENTILE.EXC | PERCENTILEX.INC, PERCENTILEX.EXC | The 90th percentile week for staffing |
| Count distinct | DISTINCTCOUNT | COUNTX over VALUES | Number of receipts or students |
Median Weekly Margin =
MEDIANX ( VALUES ( 'Date'[Week Start] ), [Gross Margin] )
Weekly Margin Std Dev =
STDEVX.S ( VALUES ( 'Date'[Week Start] ), [Gross Margin] )The median is often more useful than the mean for operational data. Two September weeks of textbook rush made the average weekly margin for textbooks look excellent, while the median showed that most weeks were thin. Standard deviation gave the managers a number for "swings wildly". Kwabena explained the sample and population forms simply: the weeks in the data are a sample of all the weeks the outlets will ever trade, so the .S forms suit forecasting questions; when the data really is the whole group, such as all sections in one term, the .P forms are fine.
Ranking with RANKX
RANKX ranks an expression over a table. It iterates the table, evaluates the expression for each row, evaluates it once more in the current context, and returns the position of the current value among the others.
Category Margin Rank =
IF (
ISINSCOPE ( 'Product Category'[Category] ),
RANKX (
ALLSELECTED ( 'Product Category'[Category] ),
[Gross Margin],
,
DESC,
DENSE
)
)Three details make this measure correct. The table argument uses ALLSELECTED on the category column, so the ranking covers all categories visible to the reader rather than only the current row's category, which would always rank first. ISINSCOPE returns true only when categories are on the rows of the visual, so the total row shows blank instead of a meaningless rank. And the ties argument DENSE gives tied categories the same rank with no gap after them; SKIP, the default, leaves a gap, as in sports rankings.
A common mistake is ranking over ALL ( 'Product Category' ) when the reader has filtered to some categories: the rank then counts categories the reader cannot see, so the top visible category might show rank 3. ALLSELECTED matches what is on screen. If the ranking must ignore the reader's category filter on purpose, for example "rank among all categories college-wide", ALL is right; the choice depends on the question.
TOPN and top-N filtering
TOPN returns the top N rows of a table by an expression. Combined with CALCULATE, it answers questions such as "sales from our five best categories".
Top 5 Category Sales =
CALCULATE (
[Outlet Sales],
TOPN ( 5, ALLSELECTED ( 'Product Category'[Category] ), [Outlet Sales], DESC )
)For simple top-N visuals, the Top N filter type in the filter pane is often enough: filter a visual to the top five categories by a measure without writing DAX. Measures like this one are for cases where the top-N result itself is a number used elsewhere, such as "share of sales from the top five".
Window functions: OFFSET, INDEX and WINDOW
DAX also has window functions, which are especially useful for comparisons with neighbouring rows. OFFSET returns a row a given distance before or after the current one, INDEX returns a row at an absolute position, and WINDOW returns a range of rows. RANK and ROWNUMBER provide ranking in the same style. These functions take a relation and an ORDERBY clause, much like windowed functions in SQL.
Sales vs Previous Week =
VAR Prev =
CALCULATE (
[Outlet Sales],
OFFSET ( -1, ALLSELECTED ( 'Date'[Week Start] ), ORDERBY ( 'Date'[Week Start], ASC ) )
)
RETURN
[Outlet Sales] - PrevVisual calculations, generally available since June 2026, offer another route to many of these comparisons. A visual calculation is a DAX calculation defined on a single visual, working on the visual's own grid of rows and columns, with simple functions such as RUNNINGSUM, MOVINGAVERAGE, PREVIOUS and RANK. They are easier to write than model measures for one-off, visual-specific comparisons. They are not stored in the model and cannot be reused by other visuals or reports, so measures remain the right choice for business definitions everyone shares.
Worked problem
Choosing what to average over
The café manager asks for "average sales". Kwabena can build AVERAGE ( 'Outlet Sales'[Sales Amount] ), AVERAGEX over receipts, or AVERAGEX over days. Which should he use, and how does he decide?
Show solution
- Ask what decision the number supports. The manager is planning staff by day.
- AVERAGE over sales lines gives the typical line value, which is useless for staffing.
- AVERAGEX over receipts gives the typical transaction value, useful for pricing but not staffing.
- AVERAGEX ( VALUES ( 'Date'[Date] ), [Outlet Sales] ) gives typical daily sales; filter Is Weekday to teaching days to exclude closed days.
Answer: Average daily sales over teaching days, using AVERAGEX over dates with a weekday filter, because the question is about staffing per day.
Counting with iterators
Counting questions often need iterators too. How many students took more than twelve credits this term? The Registration table has one row per student per section, so a count of rows counts registrations, not students. The question needs the total credits per student first, then a count of students above the threshold.
Students Over 12 Credits =
COUNTROWS (
FILTER (
VALUES ( Registration[StudentKey] ),
CALCULATE ( SUM ( Registration[Credits] ) ) > 12
)
)VALUES ( Registration[StudentKey] ) returns the students visible in the current context, such as one campus and term. For each student, CALCULATE turns the row into a filter, so SUM adds only that student's credits. FILTER keeps students above twelve, and COUNTROWS counts them. The same pattern answers many questions: outlets with sales above a target, courses with more than one section, programs with falling enrolment.
CONCATENATEX for readable labels
Not every iterator returns a number. CONCATENATEX joins text from each row, which is useful for titles and tooltips. A card title such as "Top campuses: Downtown, Lakeshore" can be built from TOPN and CONCATENATEX, and a tooltip can list the outlets included in a total. Kwabena used it for a dynamic subtitle on the outlets page that listed the outlets in the reader's current selection, so screenshots shared in email always said what they showed.
Selected Outlets Label =
"Outlets: "
& CONCATENATEX ( VALUES ( Outlet[Outlet Name] ), Outlet[Outlet Name], ", ", Outlet[Outlet Name], ASC )Worked problem
Ranking within a group
The bookstore managers want each category ranked by gross margin within its own outlet, so that each outlet has its own number 1. How should the RANKX table argument change?
Show solution
- The visual has Outlet and Category on the rows of a matrix.
- Ranking over ALLSELECTED ( 'Product Category'[Category] ) removes the visual's category filter but keeps the outlet filter from the outer row.
- So within each outlet, categories are ranked against other categories at the same outlet.
- To rank across all outlets instead, remove the outlet filter too, for example by ranking over a table of outlet and category combinations.
Answer: Keep RANKX ( ALLSELECTED ( 'Product Category'[Category] ), [Gross Margin] ); because the outlet filter remains, each outlet gets its own ranking.
Percentiles and quartiles for operations
Percentile functions helped the café managers with staffing. Rather than planning for the average day, they planned for a busy day: the 80th percentile of daily sales over the past term. PERCENTILEX.INC ( VALUES ( 'Date'[Date] ), [Outlet Sales], 0.8 ) returns the sales level that 80 percent of days fall below. A day above it is unusually busy. Quartiles follow from the same function with 0.25, 0.5 and 0.75, and a box-and-whisker explanation in a report tooltip helped managers who had not used percentiles before.
Iterators over virtual tables
An iterator's table does not have to be a model table. Functions such as SUMMARIZE, ADDCOLUMNS, SELECTCOLUMNS and VALUES build virtual tables that exist only while the measure runs. A measure for the average number of sections per student, for example, can iterate VALUES ( Registration[StudentKey] ) and count each student's distinct sections. Virtual tables keep the model free of single-purpose helper tables, and they are evaluated in the current filter context, so the same measure responds to campus and term slicers. Their cost depends on how many rows they produce, so the rule from earlier still applies: keep the iterated table as small as the question allows.
Common mistakes
MistakeCalling a measure inside an iterator over a fact table with millions of rows.
InsteadIterate the smallest table that answers the question, and use column arithmetic over fact tables.
MistakeRanking over the current row's own context, so every row ranks first.
InsteadRank over ALLSELECTED or ALL of the column being ranked, chosen to match the question.
MistakeShowing a rank on the total row.
InsteadWrap the rank in ISINSCOPE or HASONEVALUE so totals are blank.
MistakeAsking for "average" without saying average of what.
InsteadDecide the grain of the average: per line, per receipt, per day or per outlet.
Summary and key terms
- Aggregators summarize a column; iterators evaluate an expression for each row of a table and then aggregate.
- Iterators create a row context, and measures inside them trigger context transition for each row.
- Iterate small tables such as weeks or categories when calling measures; use column arithmetic over large fact tables.
- DAX has aggregator and iterator forms of average, median, minimum, maximum, standard deviation, variance and percentile.
- RANKX ranks an expression over a table; use ALLSELECTED or ALL deliberately, ISINSCOPE for totals and DENSE or SKIP for ties.
- TOPN returns the top rows by an expression; the filter pane's Top N filter covers simple cases.
- Window functions and visual calculations handle comparisons with neighbouring rows; measures remain the place for shared definitions.
- Iterator
- A function, often ending in X, that evaluates an expression for each row of a table and aggregates the results.
- SUMX
- An iterator that adds up an expression evaluated for each row.
- RANKX
- An iterator that returns the rank of the current value of an expression among a table's values.
- ISINSCOPE
- A function that tests whether a column is being used to group the current visual level.
- TOPN
- A function that returns the top N rows of a table by an expression.
- Window function
- A function such as OFFSET, INDEX or WINDOW that returns rows relative to the current one in an ordered set.
- Visual calculation
- A DAX calculation defined on a single visual and evaluated over its grid.
Practice problems
Work each problem on paper first, then reveal the answer to check.
Write a measure for revenue as quantity times unit price, line by line.
Show answer
SUMX ( 'Outlet Sales', 'Outlet Sales'[Quantity] * 'Outlet Sales'[Unit Price] )
Why is the median sometimes better than the mean for weekly margin?
Show answer
It is less affected by a few extreme weeks, such as the textbook rush, so it shows the typical week.
What does the DENSE ties option do in RANKX?
Show answer
Tied values share a rank and the next rank follows without a gap.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.