Detect Pivot Coordinates
Before the DAX engine even looks at your formula, it de- tects the “coordinates” of the current measure cell (the
Values-area cell from the pivot that is currently being calculated.)
To illustrate this, let’s use a slightly “richer” pivot:
The selected measure cell has three “coordinates”, com- ing in from the Row, Column and the Slicer –
When specifying pivot coordinates, use the Table[Column] format, as it may appear redundant initially but will prove useful when working with multiple tables.
A measure cell’s set of filter coordinates is often referred to as its Filter Context
CALCULATE Alters Filter Context
We will revisit this topic later in the book for a more comprehensive explanation For now, we mention it briefly to ensure consistency in the numbering of the steps throughout the text.
Apply Those Filter Coordinates to the Underlying Table(s)
The specified filters in the filter context are applied exclusively to the Sales table, as all three coordinates originate from it This filtering process occurs behind the scenes, affecting the Sales table based on the MonthNum, Year, and ProductKey values in the filter context.
Figure 107 Applying Filter Coordinates in Step 3: All Three Filters Get Applied to the Sales Table
Filters Follow the Relationship(s)
Covered in Chapter 10 We’ll skip this for now, too.
Power Pivot and Power BI: The Excel User's Guide to the Data Revolution
Evaluate the Arithmetic
The arithmetic in your formula is evaluated only after the filter context of a measure cell, defined by its position in the pivot, has been applied to filter the underlying table(s).
In our example, the calculation is straightforward: SUM(Sales[SalesAmt]), but more complex calculations would operate similarly on the filtered rows Essentially, functions like SUM() or COUNTROWS() are executed only after the filter context has been applied to the source tables.
Figure 108 Evaluate the arithmetic against all the rows that “survived” the filtering process
In Step 3, while the Sales[SalesAmt] column itself wasn't directly filtered, applying filters to the [ProductKey], [MonthNum], and [Year] significantly reduced the total number of rows in the Sales table Consequently, the [SalesAmt] column now reflects only a subset of its overall values, highlighting the interconnectedness of data filtering in analysis.
Return Result
The result of the arithmetic is returned to the current measure cell in the pivot, then the process starts over at step 1 for the next measure cell.
Figure 109 Result is returned back to the Pivot
The evaluation process consists of two distinct phases: the application of filters followed by arithmetic calculations This can be visualized as an assembly line with two machines, where the first is the Filter Machine and the second is the Math Machine.
Figure 110 Some people find it helpful to visualize the calculation process as an assembly line: first things go into the Filter Ma- chine, then the Math Machine.
How the DAX Engine Calculates Measures
Here is a recap of all six golden rules, which outline how the DAX engine works:
Figure 111 Measure evaluation proceeds as per steps outlined Details on some steps to be filled-in in later chapters A Few More
No “Naked Columns” in Measure Formulas
In a measure formula, referencing a column must always be done within a function; otherwise, a direct reference will result in an error For instance, using a column reference without wrapping it in a function is not permitted.
[My New Measure] Sales[Margin]
Figure 112 We enter a “naked” column reference into the measure editor, then click Check Formula…
Power Pivot and Power BI: The Excel User's Guide to the Data Revolution
Figure 113 …leading to a relatively cryptic error message.
Let’s look at that error message:
A calculation error has occurred in the 'Sales' measure, indicating that the value for the 'Margin' column cannot be determined in the current context It's essential to verify that all columns referenced in the calculation expression are present and ensure there are no circular dependencies affecting the calculation.
The error message is not very informative; it should provide more guidance When encountering this error, it's essential to interpret it as an indication that there is an unqualified column reference present in your code.
“Cannot be determined in the current context” should become a trigger phrase for you to think “I have a naked column reference somewhere in my measure formula.”
But all of the following would be valid:
Aggregation functions are essential in pivot tables, as they transform sets of rows into concise numerical summaries Calculated column formulas utilize "naked columns," while measures serve as aggregations that cannot independently reference naked columns.
Remember, naked column references are OK in calculated columns This rule only applies to measures.
Best Practice: Reference Columns and Measures Differently
Whenever we are writing a measure formula,
• To reference a column, we include the table name: TableName[ColumnName]
• To reference a measure, we omit the table name: [MeasureName]
To enhance the readability of our formulas, we use a naming convention where references with a table name indicate a column, while those without a table name signify a measure.
Additionally, there are many situations in which omitting the table name on a column reference will return an error Following this best practice avoids that issue as well.
Best Practice: Assign Measures to the Right Tables
The “Table name” box in the measure editor controls which table the measure will be assigned to in the field list.
Figure 114 If you set this dropdown to the Sales table…
Figure 115 …the measure will be “parented” to the Sales table in the field list.
Simple Rule: We assign our measures to the tables that contain the numeric columns used in the formula
This is merely good hygiene so that your model is easier to understand later (by you or by someone else)
When assigning a measure that returns values from the Sales table, it is crucial to keep it linked to the Sales table to avoid confusion with customer metrics Assigning it to the Customers table could lead to misunderstandings, as it may imply an evaluation of customer numbers instead of sales figures It's important to note that the table to which a measure is assigned does not affect the results; the outcomes remain consistent regardless of the assignment.
Power Pivot and Power BI: The Excel User's Guide to the Data Revolution
8 - CALCULATE() – Your New Favorite Function
Have you ever used the Excel function SUMIF(), or perhaps its newer cousin, SUMIFS()?
We describe CALCULATE() as “the SUMIF/SUMIFS you always wish you’d had.” You are going to love this function, be- cause it works wonders
If you've been fortunate enough to bypass the SUMIF() and SUMIFS() functions in Excel, it's time to recognize their value These powerful functions allow you to sum a specified column while excluding rows that do not meet your defined criteria For example, you can utilize SUMIF to calculate the total sales figures for entries where the Year column indicates 2012.
Does that sound familiar? It sounds a lot like the Golden Rules from the prior chapter – “filter, then arithmetic.” An interesting similarity, and CALCULATE() continues in that same tradition.
Anyway, CALCULATE() is superior to SUMIF() and SUMIFS() in three fundamental ways:
1 It has cleaner syntax This is the smallest of the three advantages, but it feels good And a happier formula writer is a better formula writer.
In Excel, the absence of specific functions like MAXIF(), MINIF(), and STDEVIF() can be frustrating, as users often seek more versatile conditional calculations However, the CALCULATE() function provides a powerful solution by enabling users to apply any aggregation function or complex multi-function expression, effectively creating an IF version for a wide range of scenarios.
3 It can be used in pivots (as part of a measure), which normal SUMIF() cannot.
CALCULATE(, , , …)
Ex: CALCULATE(SUM(Sales[Margin]), Sales[Year] 01)
Ex: CALCULATE([Sales per Day], Sales[Year] 02, Sales[ProductKey]13)
CALCULATE() in Action – a Few Quick Examples
Let’s start with a simple pivot Year on rows, [Total Sales] measure on values:
OK, let’s add a new measure, one that is always filtered to Year 02:
[2002 Sales] CALCULATE ( [Total Sales], Sales[Year] = 2002 )
Three things to note in this formula:
In the CALCULATE function, the argument can accept any valid measure name, including pre-defined measures and formula expressions suitable for defining a measure.
2 In the argument, 2002 is not in quotes That’s because the
Year column is numeric If it were a text column, we would have need- ed to use =”2002” instead.
3 We only used one argument this time, but we could use as many as we want in a single CALCULATE formula.
Figure 116 Simple pivot – the basis for our first foray into CALCULATE()
Figure 117 Our new measure matches the original measure’s 2002 value in every situation!
The results may align closely with your expectations, though they might not be exactly what you anticipated You may have expected the years 2001 and 2003 to show zeroes for the new measure, and the grand total cell might be puzzling However, it’s likely intuitive that the new measure consistently reflects the 2002 value from the original measure.
Typically, writing a CALCULATE measure that filters a column present in the pivot, such as Sales[Year], is uncommon and often lacks practical application This approach is introduced here to illustrate the concept effectively.
To enhance clarity, we can replace the Year with MonthNum in the pivot, which offers a more logical representation of the data While the overall total remains at $6.5 million, each individual cell now reflects unique sales figures for 2002 corresponding to the MonthNum from the pivot.
Figure 118 Previous results examined: each month of 2002 is returned separately, and the grand total matches all of 2002 Exactly what we want and expect!
To understand the functionality of CALCULATE(), it's essential to analyze its mechanics, as this will clarify some of the surprising outcomes observed in the initial example.
There are three key points to know about CALCULATE(), specifically about the arguments:
The arguments play a crucial role during the "filter" phase of measure calculation by altering the filter context provided by the pivot This modification occurs prior to the application of filters to the source tables and before the arithmetic phase takes place.