Chapter 4: DAX: Overview 123
in the Orders Details table. Your column would need to reference the Products table,
which in turn references the Categories table. This is, in effect, a double jump. The next
two lines of code show how (the first goes in the Products table; the second goes in the
Order Details table and assumes that the first one is named Category):
=RELATED(Categories[CategoryName])
=RELATED(Products[Category])
This is all very nice, but there is one proviso. You can’t relate a table to itself in
PowerPivot, and therefore, you can’t use RELATED() if it references a column in the
same table. Thus, you can’t create a hierarchy directly in the Employees table. This is
a self-join table, in a relational source, with the Reports To column referencing the
EmployeeID column. During the import of this table (assuming a relational source), if
you click the Details hyperlink in the Messages column of the Data Preparation row, you
will see the message that self-joins are not supported. To get around this problem, you
are probably going to have to write some SQL that joins the table to itself and unravels
the hierarchy. You might use a common table expression (CTE) to do so.
RELATED() has a sibling function, RELATEDTABLE(). In general, RELATED()
would appear in a child table (the many side of a relationship) and pull back a column
from a parent table. For example, you could add the category name to a products
table. In general, RELATEDTABLE() would appear in the parent table and reference
the matching rows in the child table. As it may well return more than one matching
row, RELATEDTABLE() returns a table rather than a column. As such, it can’t be used
to populate a column directly. However, it can be fed into another DAX function that
accepts a table as a parameter. The so-called X-functions do just that. Here’s an example:
=COUNTX(RELATEDTABLE('Order Details'),'Order Details'[OrderID])
If you have a calculated column in the Orders table, this will show how many order
lines there were in each order.
Why Use the CALCULATE() Function?
The CALCULATE() function is very popular in measures. Here, we examine why this
might be so.
Measures have filter context. As the user filters (Report Filter and/or Row Labels
or Column Labels) and/or slices (Slicers Vertical or Slicers Horizontal), they change
the context in which the measures are shown in the pivot table. By default, the
measure values will change to reflect the current context—measures are re-evaluated
every time the context is changed. This may or may not be the result you desire.