Sub topic 2
Reading Related Rows with RELATED and RELATEDTABLE
Assume you know tables, columns, one-to-many relationships, simple aggregations, and the difference between measures and calculated columns.
Reading related rows
A row context identifies one current row. RELATED uses that row and a relationship to read one value from the related table. It commonly reads from the one side while a calculated column runs on the many side.
-- Calculated column in Sales
Product Category = RELATED ( Product[Category] )RELATEDTABLE does the reverse lookup. It returns the rows on the many side that relate to the current row on the one side. Use it inside an iterator such as SUMX.
-- Calculated column in Product
Product Sales =
SUMX (
RELATEDTABLE ( Sales ),
Sales[Quantity] * Sales[Unit Price]
)The relationship must have matching keys. A missing or ambiguous relationship can produce blanks or prevent the lookup.
Iterators: SUMX, AVERAGEX, and FILTER
An iterator evaluates an expression once per row. SUMX adds those results. AVERAGEX averages them. FILTER returns only rows that satisfy a condition.
Sales Amount =
SUMX ( Sales, Sales[Quantity] * Sales[Unit Price] )
Average Sales per Customer =
AVERAGEX ( Customer, [Sales Amount] )
Products Over 1000 =
COUNTROWS (
FILTER ( Product, [Sales Amount] > 1000 )
)The surrounding filter context still limits the table being iterated. For example, a year slicer can limit Sales before SUMX calculates each line.
CALCULATE: changing filter context
CALCULATE evaluates an expression after modifying its filter context. A direct filter usually replaces an existing filter on the same column.
Red Sales =
CALCULATE (
[Sales Amount],
Product[Color] = "Red"
)Use KEEPFILTERS when the new condition must intersect with the existing selection instead of replacing it.
Red Sales Within Selection =
CALCULATE (
[Sales Amount],
KEEPFILTERS ( Product[Color] = "Red" )
)Exercise
Which function should you use to total Sales rows related to the current Product row?
Show answer
Use RELATEDTABLE inside SUMX, because RELATEDTABLE returns the current product's related Sales rows.