Wiki Power BI and DAX
SUM or SUMX: when to iterate row by row
SUM aggregates a column; SUMX, AVERAGEX and the like evaluate an expression row by row and aggregate the result. The iterated table sets the grain.
SUM adds up a column. When each row's value needs a calculation before summing, such as quantity times price, use an iterator: SUMX ( table, expression ) walks the table, evaluates the expression on each row and adds up the results. SUM is a shortcut for SUMX over a single column, so for summing a plain column there is nothing to gain by iterating.
Calculated Revenue =
SUMX ( Sales, Sales[Quantity] * RELATED ( Product[Price] ) )
Average Revenue per Product =
AVERAGEX ( Product, [Revenue] )In the first measure, RELATED fetches the price of the product on the current Sales row. In the second, the iterator walks Product and, for each product, calls [Revenue]. Calling a measure inside an iterator triggers a context transition: the current row becomes a filter. That is why [Revenue] inside the iteration adds up only that product's sales, and not the total.
Pitfall
Forgetting that the table in the first argument sets the grain of the calculation. Compare:
Average Amount per Sale = AVERAGE ( Sales[Amount] )
Average Revenue per Product = AVERAGEX ( Product, [Revenue] )The first is the average of the Sales rows; the second is the average, across products, of each one's total. They are different questions, and the "average" label in the visual hides that. Give the measure a name that carries the grain it computes.
The second pitfall is cost: a measure inside an iterator over a large table causes one context transition per row. Iterate over the smallest table that answers the question (Product, not Sales) and, when the calculation fits in a simple aggregation, prefer SUM.
Sources
Shared knowledge from Genesis Innovation. Not a claim about the person behind this site.