Sub topic 2
Pulling Values from Related Tables with `RELATED`
Assume you know tables, relationships, simple measures, and star-schema models. These examples use a Sales fact table related to a Product table by product key.
Using `RELATED` inside an iterator
RELATED follows an existing many-to-one relationship from the current row to one row in a related table. This is useful when the calculation needs columns from both tables.
Total Cost =
SUMX (
Sales,
Sales[Quantity] * RELATED ( Product[Unit Cost] )
)SUMX creates row context for each Sales row. For each row, RELATED finds that product's unit cost. The expression then calculates the row's cost before SUMX adds the results.
SUM cannot perform this calculation because it aggregates one column. SUMX evaluates an expression for every row.
Choosing the table to iterate over
The first argument controls which rows the iterator visits.
| Table expression | Typical purpose |
|---|---|
| `Sales` | Visit fact rows and calculate a value per transaction |
| `FILTER ( Sales, ... )` | Visit only rows meeting a condition |
| `VALUES ( Customer[CustomerKey] )` | Visit each visible customer once |
| `ALL ( Product[Product Name] )` | Visit every product, ignoring product filters |
Use the narrowest table that represents the calculation. Iterating millions of transaction rows is usually more expensive than iterating a smaller set of customers or products.
flowchart TD
A[Sales row context] --> B[RELATED Product Unit Cost]
B --> C[Calculate row cost]
C --> D[SUMX adds row results]Measures and context transition
A measure inside an iterator behaves differently from a column expression. When DAX evaluates a measure in row context, context transition converts the current row into filter context. The measure then calculates a result for that row or member.
Avg Sales per Customer =
AVERAGEX (
VALUES ( Customer[CustomerKey] ),
[Sales Amount]
)Here, VALUES supplies one visible customer per row. Context transition makes each customer key filter [Sales Amount].
`AVERAGEX` and blanks
AVERAGEX evaluates an expression for each row and averages the nonblank results. Blank results are excluded rather than treated as zero.
Avg Daily Sales =
AVERAGEX (
VALUES ( 'Date'[Date] ),
[Sales Amount]
)This returns the average sales for days with a nonblank sales result.
Exercise
Why does SUMX use RELATED ( Product[Unit Cost] ) instead of directly referencing Product[Unit Cost]?
Show answer
The iterator has a current Sales row, and RELATED follows the relationship to retrieve the matching product row.