Power Pivot & DAX course · Lesson 9 of 16

Iterators in DAX: SUMX, AVERAGEX, MAXX and RANKX

Row-by-row DAX: SUMX for cost and margin, AVERAGEX per customer, MAXX, CONCATENATEX and ranking products with RANKX and HASONEVALUE.

Intermediate 20 min read

Plain aggregation functions such as SUM and AVERAGE accept a single column. Real business questions are rarely that tidy: cost is quantity times unit cost, the average should be per customer rather than per order line, and a ranking needs to compare each product with all others. For these you use iterators, the DAX functions ending in X (SUMX, AVERAGEX, MAXX, MINX, COUNTX) and their relatives RANKX and FILTER. They walk through a table row by row, evaluate an expression for each row, and then aggregate the results.

How an iterator works

DAX
SUMX ( <table>, <expression> )
Every X function has the same shape: a table to walk through, and an expression to evaluate per row.
  1. The table argument is evaluated in the current filter context. In the Accessories row of a PivotTable, Sales contains only accessory sales.
  2. For each row of that table, the iterator creates a row context and evaluates the expression, so column references mean this row's value.
  3. The per-row results are aggregated: summed by SUMX, averaged by AVERAGEX, and so on.

This is the combination of filter and row context from Filter context and row context in DAX in action.

SUMX: cost and margin without extra columns

Sales stores Qty and Amount, but cost per unit lives in Products. Instead of a calculated column, write one measure:

DAX
Revenue := SUM ( Sales[Amount] )
Cost := SUMX ( Sales, Sales[Qty] * RELATED ( Products[Cost] ) )
Margin := [Revenue] - [Cost]
Margin % := DIVIDE ( [Margin], [Revenue] )
RELATED fetches the product's cost for the current Sales row.
ABCDE
1ProductIDProductCategoryPriceCost
2P1LaptopComputers950700
3P2MouseAccessories125
4P3MonitorDisplays189120
5P4KeyboardAccessories3518
6P5TabletComputers420300

Products: unit Price and Cost.

ABCDE
1CategoryRevenueCostMarginMargin %
2Accessories74534839753.3%
3Computers49503600135027.3%
4Displays94560034536.5%
5Grand Total66404548209231.5%

Products[Category] on rows. Margin % formatted as a percentage.

For Computers, SUMX visits four rows: 2 laptops × 700, 4 tablets × 300, 1 laptop × 700 and 1 tablet × 300, giving 3,600. Revenue is 4,950, so the margin is 1,350, or 27.3%. The result is identical to the calculated-column approach of Calculated columns vs measures in Power Pivot, but nothing extra is stored in the model.

Tip. Iterating a fact table with a simple expression is fast: the engine is built for it. Millions of rows in SUMX ( Sales, Sales[Qty] * Sales[Price] ) are no problem. What becomes slow is calling complex measures for every row of a huge table, or nesting one iterator inside another over two large tables.

AVERAGEX: average over the right thing

AVERAGE ( Sales[Amount] ) averages order lines. Managers often want the average per customer instead. Iterate over the list of customers, compute revenue for each, then average:

DAX
Avg per Order := AVERAGE ( Sales[Amount] )
Avg per Customer := AVERAGEX ( VALUES ( Sales[CustomerID] ), [Revenue] )
VALUES returns the distinct customers visible in the current cell.
ABCDE
1CategoryRevenueCustomersAvg per CustomerAvg per Order
2Accessories7453248.33186.25
3Computers495031,650.001,237.50
4Displays9452472.50472.50
5Grand Total664041,660.00664.00

Products[Category] on rows; averages with 2 decimals.

In the Accessories row, three customers bought: Anna Weber 175, Brook Dental 330 (two orders) and Carter & Co 240. Their average is 248.33. Because [Revenue] is a measure, it is evaluated for each customer through context transition, so each customer's revenue is filtered correctly. Writing SUM ( Sales[Amount] ) instead of [Revenue] inside AVERAGEX would give the wrong answer, because a bare SUM does not trigger context transition; you would need CALCULATE ( SUM ( Sales[Amount] ) ).

Other iterators

FunctionReturnsExample
SUMXSum of the expressionSUMX ( Sales, Sales[Qty] * RELATED ( Products[Cost] ) )
AVERAGEXAverage of the expressionAVERAGEX ( VALUES ( Sales[CustomerID] ), [Revenue] )
MAXX / MINXLargest / smallest valueMAXX ( VALUES ( Customers[Customer] ), [Revenue] )
COUNTXCount of non-blank resultsCOUNTX ( Products, [Revenue] )
CONCATENATEXText joined with a separatorCONCATENATEX ( VALUES ( Products[Product] ), Products[Product], ", " )
FILTERThe rows where the condition is trueFILTER ( Products, [Revenue] > 1000 )

MAXX ( VALUES ( Customers[Customer] ), [Revenue] ) returns the revenue of the best customer in the current cell, 2,495 at the grand total. CONCATENATEX is a lovely way to list the products bought by a customer in a single PivotTable cell.

RANKX: ranking products

DAX
RANKX ( <table>, <expression>, [value], [order], [ties] )
order: DESC (default, largest = 1) or ASC; ties: SKIP (default) or DENSE.

RANKX evaluates the expression for every row of the table, then finds where the current cell's value falls in that list. The table must contain all products, otherwise each product would be ranked against only itself. That is where ALL from Removing filters: ALL, ALLEXCEPT, ALLSELECTED and REMOVEFILTERS comes in:

DAX
Rank (no fix) := RANKX ( ALL ( Products[Product] ), [Revenue] )

Product Rank :=
IF (
    HASONEVALUE ( Products[Product] ),
    RANKX ( ALL ( Products[Product] ), [Revenue] )
)
The second version shows a rank only when exactly one product is in context.
ABCD
1ProductRevenueRank (no fix)Product Rank
2Keyboard38544
3Laptop285011
4Monitor94533
5Mouse36055
6Tablet210022
7Grand Total66401

Products[Product] on rows, sorted alphabetically.

Laptop has the highest revenue (2,850) and ranks 1; Mouse, with 360, ranks 5. The Grand Total row of the first measure shows a meaningless 1: the total revenue of 6,640 is compared with the individual products and is larger than all of them. HASONEVALUE returns TRUE only when the filter context contains exactly one product, so Product Rank stays blank on totals. Without a third argument for IF, the result is blank.

Ties and order

  • With the default SKIP, two products tied for 2nd are both 2 and the next one is 4, like a sports table.
  • With DENSE, the next one is 3: RANKX ( ALL ( Products[Product] ), [Revenue], , DESC, DENSE ). Note the empty third argument.
  • Use ASC to rank the smallest value first, for example the cheapest supplier or the fastest delivery time.
Watch out. If you add Category to rows above Product, ALL ( Products[Product] ) still ranks each product against all products, not within its category. To rank within the category, use ALLSELECTED ( Products[Product] ) with the category filter kept, or rank over CALCULATETABLE ( VALUES ( Products[Product] ), ALL ( Products[Product] ) ). Check the numbers on a small example before trusting them.

Practice

  1. Write Units Value at Cost := SUMX ( Sales, Sales[Qty] * RELATED ( Products[Cost] ) ) and check the grand total.
  2. Create Best Customer Revenue := MAXX ( VALUES ( Customers[Customer] ), [Revenue] ) and put Region on rows.
  3. Create a Customer Rank measure with RANKX over ALL ( Customers[Customer] ) and protect it with HASONEVALUE.

Check yourself

1. Why use SUMX ( Sales, Sales[Qty] * RELATED ( Products[Cost] ) ) instead of SUM?

2. What table should AVERAGEX iterate to get the average revenue per customer?

3. Why does RANKX ( ALL ( Products[Product] ), [Revenue] ) show 1 at the Grand Total?

4. Which function hides the rank on total rows?

5. With ties = DENSE and two products tied for 2nd, what is the next rank?