Excel Dax Tutorial
Excel Dax Tutorial
Audience
This tutorial has been designed for all those readers who depend heavily on MS-Excel to
prepare charts, tables, and professional reports that involve complex data. It will help all
those readers who use MS-Excel regularly to analyze data. Professionals who use data
modeling and data analysis for reporting and decision-making purposes will benefit from
this.
Prerequisites
This tutorial is an extension to Excel Power Pivot tutorial, hence it is a good idea to brush
up on the Excel Power Pivot tutorial before you delve into DAX. Knowledge of Excel
Functions and Excel Formulas is not necessary for this tutorial, as DAX is entirely for the
Data Model in the Power Pivot window.
All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.
We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com.
i
DAX
Table of Contents
About the Tutorial .................................................................................................................................... i
Audience .................................................................................................................................................. i
Prerequisites ............................................................................................................................................ i
DAX Formulas.......................................................................................................................................... 2
DAX Syntax.............................................................................................................................................. 3
DAX Formulas.......................................................................................................................................... 4
ii
DAX
iii
DAX
How DAX Handles Blanks, Empty Strings, and Zero Values? .................................................................. 50
7. DAX OPERATORS............................................................................................................. 52
iv
DAX
v
DAX
Dependencies...................................................................................................................................... 107
vi
DAX
Date Based on Date Parts Extracted from a Text Date ......................................................................... 129
23. DAX SCENARIOS CONDITIONAL VALUES & TESTING FOR ERRORS ................................. 135
Applying a Filter to Show only the Top Few Items ............................................................................... 141
vii
1. DAX Overview DAX
DAX stands for Data Analysis Expressions. DAX is a formula language and is a collection
of functions, operators, and constants that can be used in a formula or expression to
calculate and return one or more values. DAX is the formula language associated with the
Data Model of Excel Power Pivot.
It is not a programming language, but is a formula language that allows the users to define
custom calculations in calculated columns and calculated fields (also known as measures).
DAX helps you create new information from the data that is already present in your Data
Model. DAX formulas enable you to perform data modeling, data analysis, and use the
results for reporting and decision making.
DAX includes some of the functions that are used in Excel formulas, but with modified
functionality and additional functions that are designed to work with relational data and
perform dynamic aggregation.
Importance of DAX
The foundation of DAX is the Data Model that is the Power Pivot database in Excel. Data
Model consists of tables between which relationships can be defined so as to combine the
data from different sources. The data connections to the Data Model can be refreshed as
and when the source data changes. Data Model makes the use of the Power Pivot xVelocity
in-memory analytics engine (VertiPaq) that makes the data operations to be as quick as
possible in addition to accommodating several thousands of rows of data. For more
information on Data Model, refer to the tutorial Power Pivot.
DAX in conjunction with Data Model enables several power features in Excel Power Pivot,
Power PivotTables, Power PivotCharts and Power View. You can use DAX to solve a number
of basic calculations and data analysis problems.
DAX is also useful in Power BI to create a new Power BI Desktop file and import some data
into it. Further, DAX formulas provide capabilities such as analyzing growth percentage
across product categories and for different date ranges, calculating year-over-year growth
compared to market trends and many others as well.
Learning how to create effective DAX formulas will help you get the most out of your data.
When you get the information you need, you can begin to solve real business problems
that affect your bottom line. This is the power in Power BI and DAX will help you get there.
1
DAX
This tutorial also introduces DAX Functions that are like Excel Functions, but with some
variations. A comparison of Excel Functions and DAX Functions is provided to help you
distinguish both. Similarly, Excel formulas and DAX formulas are compared and the
similarities and differences are discussed. A good understanding of these differences would
help you in writing effective DAX formulas efficiently.
Knowledge of Excel Functions and Excel Formulas is not necessary for this tutorial, as DAX
is entirely for the Data Model in the Power Pivot window. You will get into an Excel
worksheet only to view the Power PivotTables, Power Pivot Charts and Power View
visualizations that are based on Data Model. However, if you are an Excel professional
with good amount of knowledge in Excel Functions and Formulas, better make a note of
what is mentioned in the previous section and the details given in the course of this
tutorial.
Calculated Columns
Calculated columns are the columns that you can add to a table in the Data Model, by
means of a DAX formula. You have already learnt about them in Excel Power Pivot tutorial,
but you will learn in detail in the chapter Calculated Columns as DAX is all about
calculated columns, calculated fields, and DAX functions.
The calculated fields were named as measures in the Excel versions prior to Excel 2013.
They are renamed back to measures in Excel 2016. In this tutorial, we will refer them as
calculated fields. But, note that the terms - calculated fields and measures - are
synonymous and refer to the same in all aspects.
You can edit a calculated field after it is defined and stored. You can change the DAX
formula used in the definition or you can rename the calculated field. You will learn about
this in the chapter Editing a Calculated Field. You can delete a calculated field. Refer
to the chapter Deleting a Calculated Field.
DAX Formulas
DAX formulas form the heart of the DAX language. You can create calculated fields and
calculated columns by defining them with DAX formulas. You can write DAX formulas for
the data analysis operations. DAX formulas do not refer to the individual cells or range of
cells in the table, but refer to the tables and columns in the Data Model. A column in a
table in the Data Model must contain the same data type.
DAX formulas contain the tables, columns, calculated columns, calculated fields, DAX
operators, and DAX functions. Refer to the chapter DAX Formulas to learn in detail.
2
DAX
DAX Syntax
As is the case with any language, DAX, the formula language also has a syntax. Your DAX
formulas should follow DAX syntax, or else, you will either get errors at design time or at
run time or you will receive incorrect results.
DAX Operators
DAX is a formula language and hence makes the use of the operators in defining the
formulas. DAX has the following types of operators
DAX Functions
Excel 2013 has 246 DAX functions that you can use in DAX formulas. You will learn about
these functions at the category level in the chapter DAX Functions. However, for details
on each DAX function syntax, parameters, usage and return values, you have to refer to
our tutorial on DAX Functions. The section names used for the description of each DAX
function is given in the chapter Understanding DAX Functions.
As DAX functions are required in writing the DAX formulas and the results of the DAX
functions used depend on the context they are used, you might have to go back and forth
between these two tutorials to get a grasp on DAX that you will use in Data Modeling with
DAX and Power BI.
3
DAX
DAX Formulas
DAX is a formula language and you have to get the most of it in writing the DAX formulas.
Refer to the chapter - DAX Formulas to learn about the formula syntax and how to create
them easily and correctly.
The results of the DAX formulas change whenever the data is refreshed and whenever the
DAX formulas are recalculated. You have to understand the difference between data
refresh and recalculation. Refer to the chapter - Updating the Results of DAX
Formulas.
Data in the Data Model is expected and subjected to change from time to time. This is
because the data is used for data analysis activities that require up-to-date data at any
point of time. To understand the different ways of refreshing data, refer to the chapter -
Updating Data in Data Model.
You will understand the different types of DAX formula recalculation in the chapter -
Recalculating DAX Formulas.
DAX formula recalculations have to consider data dependencies and follow a specific order.
Otherwise, you might get errors or erroneous results. Refer to the chapter -
Troubleshooting DAX Formula Recalculation for details.
You will get an insight into some of the common DAX formula errors and you will learn
how to fix those errors, in the chapter - DAX Formula Errors.
DAX Scenarios
If you start learning a new language, the best way of getting acquainted to the language
is by understanding where to use what. Similarly, DAX being a formula language meant
for data analysis, you need to understand the various scenarios where it can be used.
DAX Scenarios
Scenarios - Performing Complex Calculations
Scenarios - Working with Text and Dates
Scenarios - Conditional Values and Testing for Errors
4
DAX
5
2. DAX Calculated Columns DAX
A calculated column is a column that you add to an existing table in the Data Model of
your workbook by means of a DAX formula that defines the column values. Instead of
importing the values in the column, you create the calculated column.
You can use the calculated column in a PivotTable, PivotChart, Power PivotTable, Power
PivotChart or Power View report just like any other table column.
For example, you can create one calculated column to extract Year from the existing
column Date, with the DAX formula
=YEAR ([Date])
YEAR is a DAX function and Date is an existing column in the table. As seen, the table
name is enclosed in brackets. You will learn more about this in the chapter DAX Syntax.
When you add a column to a table with this DAX formula, the column values are computed
as soon as you create the formula. A new column with the header CalculatedColumn1 filled
with Year values will get created.
Column values are recalculated as necessary, such as when the underlying data is
refreshed. You can create calculated columns based on existing columns, calculated fields
(measures), and other calculated columns.
6
DAX
7
DAX
As seen in the above screenshot, the rightmost column has the header Add Column.
The pointer will appear in the formula bar. That means you are adding a column with a
DAX formula.
8
DAX
As can be seen in the above screenshot, the rightmost column with the header Add
Column is highlighted.
Press Enter.
It will take a while (few seconds) for the calculations to be done. Please wait.
The new calculated column will get inserted to the left of the rightmost Add Column.
As shown in the above screenshot, the newly inserted calculated column is highlighted.
Values in the entire column appear as per the DAX formula used. The column header is
CalculatedColumn1.
9
DAX
As seen in the above screenshot, the name of the calculated column got changed.
10
DAX
You can also rename a calculated column by right-clicking on the column and then clicking
on Rename in the dropdown list.
Just make sure that the new name does not conflict with an existing name in the table.
As you can see in the above screenshot, the dropdown list has the possible data types for
the columns. In this example, the default (Auto) data type, i.e. the Whole Number is
selected.
Changing or deleting relationships between the tables. This is because the formulas
that use columns in those tables will become invalid.
11
DAX
Performance Issues
As seen earlier in the example of Olympics results, the Results table has about 35000 rows
of data. Hence, when you created a column with a DAX formula, it had calculated all the
35000+ values in the column at once, for which it took a little while. The Data Model and
the tables are meant to handle millions of rows of data. Hence, it can affect the
performance when the DAX formula has too many references. You can avoid the
performance issues doing the following
If your DAX formula contains many complex dependencies, then create it in steps
saving the results in new calculated columns, instead of creating a single big
formula at once. This enables you to validate the results and assess the
performance.
Calculated columns need to be recalculated when data modifications occur. You can
set the recalculation mode to manual, thus saving frequent recalculations.
However, if any values in the calculated column are incorrect, the column will be
grayed out, until you refresh and recalculate the data.
12
3. DAX Calculated Fields / Measures DAX
A calculated field in a table in a Data Model is the field obtained by a DAX formula. In
earlier versions of Power Pivot, the calculated field was termed as a measure. In Excel
2013, it was renamed as a calculated field. However, it is renamed back to measure in
Excel 2016. If you refer to any documentation, you can observe a mix up of these two
terms. Note that the terms calculated field and measure are synonymous. In this tutorial,
we use the term calculated field.
You can create a calculated field based on standard aggregation functions, such as COUNT
or SUM, or by defining your own DAX formula.
Following is the difference between the calculated field and the calculated column -
A calculated column with the calculated results can be used in ROWS, COLUMNS
and FILTERS areas also.
13
DAX
As seen in the above screenshot, the Results table has a field Medal that contains the
values Gold, Silver, or Bronze for each of the rows containing Sport Event - Country
Date combination. Suppose you want medal count for each country, then you can create
a calculated field Medal Count with the following DAX formula
Click the cell in the calculation area below the Medal column in the Results table.
The cell will be highlighted.
14
DAX
Press Enter.
As seen in the above screenshot, the calculated field appears in the selected cell, showing
the value as 34,094. This number is the total number of rows in the Results table. Hence,
it does not make much sense at the first look. As discussed earlier, the real use of a
calculated field can be seen only by adding it to a Power PivotTable or a Power PivotChart.
15
DAX
16
DAX
As you can observe, Medal Count is added to VALUES area and Country is added to ROWS
area. The PivotTable is created with the field Country values appearing in the rows. And
for each row, the Medal Count value is calculated and displayed. That is the way, the
calculated field evaluates the DAX formula used and displays the values.
Add the field Sport from the Results table to ROWS area.
As you can see in the above screenshot, Medal Count is calculated for each Country -
Sport-wise and a Subtotal for the Country itself.
17
DAX
An implicit calculated field is created in the Power PivotTable Fields list pane.
An explicit calculated field is created either in the table in the Power Pivot
window, or from the PowerPivot Ribbon in the Excel window.
Count of Medal appears in the Values area. Count of Medal column will be added to the
PivotTable.
18
DAX
Click the down arrow in the Count of Medal box in VALUES area.
Click the Value Field Settings in the dropdown list.
19
DAX
Click Percentage.
Type 0 in decimal places.
Click OK.
Click OK in the Value Field Settings dialog box.
Select Do Not Show Subtotals.
20
DAX
You created another implicit calculated field % Medals and as you can observe, for each
Country, the percentage of Medals Sport-wise are displayed.
They are volatile. That means, if you deselect the field you used for calculated
field, it will be removed. If you want to display it again, you have to once again
create it.
Their scope is limited to the PivotTable or PivotChart in which they are created.
If you create another PivotTable in another worksheet, you have to create the
calculated field again.
On the other hand, explicit calculated fields will get saved with the table and will be
available whenever you select that table.
In the calculation area in a Table in the Data Model. You have already learnt this in
the section Creating Calculated Field in a Table.
From PowerPivot Ribbon in the Excel table. You will learn this way of creating an
explicit calculated field in the next section.
21
DAX
22
DAX
As you can observe, you can define the category and format of the calculated field in this
dialog box. Further, you can use the IntelliSense feature to understand the usage of the
functions and to use the AutoComplete feature to easily complete the names of the
functions, tables, and columns. For details on IntelliSense feature, refer to the chapter
DAX Formulas.
23
4. DAX Editing a Calculated Field DAX
You can edit a calculated field to modify it. But, before you edit a calculated field, you
should know where it is stored. That means, in which table the calculated field is stored.
This holds both for implicit and explicit calculated fields. A calculated field can be
associated with only one table in a Data Model.
Click the Advanced tab on the Ribbon in the Power Pivot window.
Click the Show Implicit Calculated Fields.
24
DAX
As you can see in the above screenshot, Show Implicit Calculated Fields is highlighted on
the Ribbon. If it is not highlighted, click it again.
You can also observe that there are 4 checkboxes Columns, Calculated Fields,
Hierarchies, and KPIs. By default, all the 4 are selected.
As seen in the above screenshot, only the Results table has fields displayed. The other two
tables are blank. This shows that only the Results table has calculated fields. You can also
observe that the implicit calculated fields have an icon displayed, whereas the explicit
calculated field Medal Count does not have that icon.
25
DAX
As seen in the above screenshot, the calculated fields appear in the calculation area of the
table.
26
DAX
Click the calculated field in the table in data view of the Data Model.
Select the formula in the formula bar to the right side of :=.
You will learn more about the DAX formulas in the subsequent chapters.
27
DAX
You will learn more about the DAX Syntax in the subsequent chapters.
The name will get into editing mode. Type the new name for the calculated field.
28
DAX
Manage Calculated Fields dialog box appears. The names of the explicit calculated fields
in the Data Model appear in the dialog box.
29
DAX
30
DAX
31
DAX
Note: It does not really matter where the calculated field is within the calculation area of
the table because the data references in the DAX formula of the calculated field are by the
column names and are stated explicitly.
32
5. DAX Deleting a Calculated Field DAX
You can delete both explicit and implicit calculated fields. There are several ways of doing
so, which you will learn in this chapter.
However, you need to remember the following points before deleting a calculated field
An explicit calculated field can be used in more than one PivotTable and/or
PivotChart. Hence, you need to make sure that deleting the explicit calculated field
does not affect any of the reports that you have already generated.
An explicit calculated field can be used in the calculations of other explicit calculated
fields. Hence, you need to make sure that the explicit calculated field is not used
in any of the calculations of other explicit calculated fields.
You cannot create an explicit calculated field, if the name conflicts with the name
of an implicit calculated field. Hence, you might have to delete that implicit
calculated field before creating the explicit calculated field.
33
DAX
Click Delete from Model. The explicit calculated field will get deleted.
34
DAX
Click Delete from Model. The explicit calculated field will get deleted and it will not be seen
in the fields list of the data table.
35
DAX
36
DAX
Click Yes. Information message that the Data Model is changed appears at the top.
Click the Close button in the dialog box.
The explicit calculated field will get deleted and it will not be seen in the
PivotTable/PivotChart Fields list in the workbook.
37
DAX
Click Delete from Model. The implicit calculated field will get deleted.
38
DAX
Click Delete from Model. The implicit calculated field will get deleted and it will not be seen
in the fields list of the data table.
39
6. DAX Syntax DAX
Before you proceed to learning DAX Syntax, you have to understand the difference
between Excel formulas and DAX formulas.
Excel formulas are typed in the formula DAX formulas are typed in the formula bar
bar in the Excel window. in the Power Pivot window.
40
DAX
Excel does not support any implicit data DAX performs implicit data type conversions
conversions. during calculations.
After the equals sign, you can provide an expression that evaluates to a scalar
value, or an expression that can be converted to a scalar value. These include the
following -
o A scalar constant.
o The result of a DAX function and its required arguments. Some DAX functions
return a table instead of a scalar value, and must be wrapped in a DAX
function that evaluates the table and returns a scalar value. Unless the table
is a single column, single row table, it is treated as a scalar value.
o Most DAX functions require one or more arguments, which can include tables,
columns, expressions and values. However, some DAX functions, such as PI,
do not require any arguments, but always require parentheses to indicate
the null argument. For e.g., you must always type PI (), but not PI. You can
also nest DAX functions within other DAX functions.
Important Note: DAX formulas can behave differently depending on whether they are
used in a calculated column or in a calculated field. You must always be aware of the
context and how the data that you use in the DAX formula is related to other data that
might be used in the calculation. You will learn more about this in the chapter DAX
Context.
Examples
=[First Name] & [Last Name]
=CONCATENATE ([First Name], [Last Name])
Profit:=[Sales] [Costs]
The first two are DAX formulas for calculated columns, whereas the third one is a DAX
formula for a calculated field.
41
DAX
DAX Functions
As in the case of Excel formulas, DAX formulas can also contain DAX functions. DAX has
following types of functions
Aggregation Functions
Date and Time Functions
Time Intelligence Functions
Filter Functions
Information Functions
Logical Functions
Math and Trig Functions
Other Functions
Parent and Child Functions
Statistical Functions
Text Functions
You will learn more about these in the chapter - DAX Functions.
The table names are case insensitive. i.e., Results, RESULTS, results all these
represent the same table.
Each calculated column and calculated field that you add to a Data Model must be
associated with a specific table.
o When you create a calculated column, you will do it within a table, thus
associating it implicitly with that table.
o When you create a calculated field, you will create it - either within a table
in the Power Pivot window or from the Excel window specifying the name
of the table where the calculated field definition should be stored.
In both the cases, the calculated field is termed as explicit calculated field and is associated
with a table.
42
DAX
Table names must be enclosed in single quotation marks if they contain spaces,
other special characters, or any non-English alphanumeric characters.
Each calculated field name must be unique within a Data Model. The table name is
optional in front of a calculated field name as it is always associated with a specific
table.
The columns can be referenced with unqualified column names if there is no name
conflict. An unqualified column name is just the column name, enclosed in
brackets. For e.g. [Medal]. When you are referencing a scalar value from the same
row of the current table, you can use the unqualified column name.
However, if the same column name is used in more than one table, then the column
has to be referenced with fully qualified column name. The fully qualified column
name is the table name, followed by the column name in square brackets. For e.g.
Results[Medal].
o VALUES.
o ALL and ALLEXCEPT.
o CALCULATE and CALCULATETABLE - in a filter argument.
o RELATEDTABLE.
o DAX time intelligence functions.
43
DAX
You must enclose the table names in quotation marks, if the name contains any characters
outside the ANSI alphanumeric character range, regardless of whether your locale
supports the character set or not. For e.g., if a table name is written in Cyrillic characters,
such as , the table name must be enclosed in quotation marks even though it
does not contain spaces.
You can use the formula AutoComplete feature, as it will then be just a matter of selecting
the fully qualified names of columns from the dropdown list, making your job easier and
error proof.
Leading or trailing spaces, unless the spaces are enclosed by name delimiters, brackets,
or single apostrophes. Control characters.
The following characters are not valid in the names of Power Pivot objects:
.,;':/\*|?&%$!+=()[]{}<>
You cannot create calculated rows by using DAX. You can create only calculated
columns and calculated fields.
When defining calculated columns, you can nest functions to any level (a maximum
being 64 that is a bit too much).
DAX has several functions that return a table. Typically, you use the values
returned by these DAX functions as an input to other DAX functions, which require
a table as an input.
44
DAX
Not a Number.
NaN
DAX returns NaN for 0/0 and Infinity/Infinity.
If you divide an expression by Infinity, you will not get an error, as DAX returns 0.
DAX Operators
The following table lists some DAX operators.
+ Addition
- Subtraction/ Sign
* Multiplication
Arithmetic Operators
/ Division
^ Exponentiation
= Equal to
> Greater than
< Less than
Comparison Operators >= Greater than or equal to
<= Less than or equal to
<> Not equal to
&& AND
Logical Operators
|| OR
45
DAX
DAX operators and Excel operators behave in a similar way with some exceptions. You will
learn more about DAX operators in the chapter - DAX Operators.
You can use a table containing multiple columns and multiple rows of data as an
argument to a DAX function.
Some DAX functions return tables, which are stored in memory and can be used as
arguments to other DAX functions.
Datetime is another new data type in Data Model that is used for date and time values.
DAX functions that require date and/or time as arguments, require the datetime data type.
True
Boolean
False
46
DAX
Note: Data Model does not support the use of the variant data type used in Excel. Hence,
when you load or import data, ensure that the data in each column of a table is of
consistent data type.
DAX functions return error in case of data type incompatibility. Ensure that the data type
of each column in a table is as required. If not, you can explicitly set the data type from
the Ribbon in the Power Pivot window.
You can learn about the data types required for each DAX function in the tutorial - DAX
Functions in this tutorials library.
47
DAX
However, there are some limitations on the values that can be successfully converted. If
a value or a column has a data type that is incompatible with the current operation, DAX
returns an error.
Example of implicit data conversion in DAX: Suppose you have a DAX formula wherein
you are adding a number to a Date. DAX interprets it in the context of function that is
used. Both the arguments are converted to a common data type and the result is returned
in the intended data type.
The type of conversion that is performed is determined by the operator, which casts the
values it requires before performing the requested operation. In the following sections,
you can find the tables of implicit data conversions for the following operators
Addition (+)
Subtraction (-)
Multiplication (*)
Division (/)
Comparison Operators
Each of the tables list the operators and indicate the conversion that is performed on each
data type in the column when it is paired with the data type in the intersecting row.
For example, if A is of Currency data type and B is a Real data type, then while calculating
A+B, DAX converts A into Real and adds it to B. The result will be a Real data type.
48
DAX
For example, if A is of Integer data type and B is of Real data type, then while calculating
A-B, DAX converts A into Real and subtracts B from A. The result will be a Real data type.
Note: Data Model also supports the unary operator, - (negative), but this operator does
not change the data type of the operand.
For example, if A is of Real data type and B is of Currency data type, then to calculate
A*B, DAX converts A to Currency data type and multiplies A with B. The result will be a
Currency data type.
For example, if A is Currency data type and B is of Real data type, then while calculating
A/B, DAX will convert A to Real number and performs the division. The result will be a Real
data type.
49
DAX
Numbers and datetime values are considered to have the same rank.
For numeric or datetime types, data conversions are performed implicitly as shown
in the following table:
Comparison
INTEGER CURRENCY REAL DATETIME
Operator
INTEGER INTEGER CURRENCY REAL REAL
CURRENCY CURRENCY CURRENCY REAL REAL
REAL REAL REAL REAL REAL
DATETIME REAL REAL REAL DATETIME
How DAX handles blanks in DAX formulas or DAX functions depends on the individual
operation such as addition or concatenation or the specific DAX function.
50
DAX
Examples
BLANK + 5 5
BLANK * 5 BLANK
5 / BLANK Infinity
0 / BLANK NaN
51
7. DAX Operators DAX
DAX is a formula language comprising of functions, operators, and values that can be used
in a formula or expression, to calculate and return one or more values.
You can use DAX operators to compare values, perform arithmetic calculations, and
concatenate strings. In this chapter, you will learn about DAX operators and how to use
them.
Example
Arithmetic Operator Mathematical Operation Result
+ Addition 5+4 9
Subtraction 5-4 1
-
Sign -4 -4
* Multiplication 5*3 15
/ Division 16/4 4
^ Exponentiation 4^2 16
The above DAX arithmetic operators are known as binary operators, meaning they
combine two values on either side, as you can observe in the examples above.
52
DAX
The DAX arithmetic operators + and can also be used as unary operators, meaning that
the DAX operator can be used only with one value. For example, +5, -4. These unary
operators can be used with any data type. However, there is a subtle difference between
the two
The + operator when used with a value or a result, it does not convert the data
type of the value. It is just ignored. For example, + Seasons is same as Seasons.
On the other hand, the operator when used with a value or a result, converts the
data type of the value to a negative numeric value. For example, Seasons = -4
if the value of Seasons is 4.
Text
Concatenation Example
Operation Result
Operator
53
DAX
Examples
! (1=1) results in FALSE, because 1=1 is TRUE.
! (1 <> 1) results in TRUE, because 1 <> 1 is FALSE.
(1=1) && (5>4) results in TRUE, because both are TRUE.
(5>4) && (5=4) results in FALSE, because 5=4 is FALSE.
(1=1) || (5=4) results in TRUE, because 1=1 is TRUE.
(2=4) || (5=4) results in FALSE, because both are FALSE.
54
DAX
1 ^ Exponentiation
2 Sign
4 ! NOT
6 & Concatenation
All expressions always begin with an equal sign (=). The equal sign indicates that
the succeeding characters constitute an expression.
To the right of the equal sign, you will have the operands connected by the DAX
operators. For example, = 5+4>5.
= 5*6-3.
Expressions are always read from left to right, and the calculations are done in that
sequence, based on the DAX operator precedence given in the previous section.
If the DAX operators have equal precedence value, they are evaluated from the left
to right. For example, =5*6/10. Both * and / have same the precedent order.
Hence, the expression is evaluated as 30/10 = 3.
If the DAX operators in the expression have different precedence values, then they
are evaluated in the precedence order from the left to right.
o =5+4>7. Default precedence is + first and > next. Hence, the expression
is calculated from the left to right. - 5+4 is calculated first resulting in 9
and then 9 > 5 is evaluated that results in TRUE.
55
DAX
For example,
= 5*6-3 evaluates to 27 with the DAX default operator precedence order. If you use
parenthesis to group the operands and operators as = 5*(6-3), then 6-3 is calculated first
resulting in 3 and then 5*3 is calculated which results in 15.
=2*5-6*3 evaluates to -8 with the DAX default operator precedence order. If you use
parenthesis to group the operands and operators as = 2*(5-6)*3, then 5-6 is calculated
first resulting in -1 and then 2*(-1)*3 is calculated which results in -6.
As you can see, with the same operands and operators, different results are possible by
the way you group them. Hence, when you use the DAX operators in the DAX formulas,
you should pay attention to how the computation sequence is to be.
DAX is more powerful than Excel because of its underlying memory resident
computation engine.
In some cases, the results of calculations or the behavior of functions in DAX may not be
the same as in Excel. This is due to the differences in the following -
56
DAX
For example, you have to compare two operands of different data types, say a number
resulting from a formula, such as =[Amount] * 0.08 and an integer. The first number can
be a decimal number with many decimal places, whereas the second number is an integer.
Then DAX handles it as follows
First, DAX will convert both the operands to real numbers using the largest numeric
format that can store both kinds of numbers.
In contrast, Excel tries to compare values of different data types without first coercing
them to a common data type. For this reason, you might find different results in DAX and
in Excel for the same comparison expression.
Further, in Excel formulas, you can refer to a single cell, or an array or a range of cells. In
DAX formulas, you cannot refer to any of these. The DAX formula references to data should
be by tables, columns, calculated fields, and calculated columns.
If you copy formulas from Excel and paste them in DAX, ensure the correctness of the
DAX formula as DAX syntax is different from Excel formula syntax. Also, even if a function
has the same name in DAX and Excel, its parameters might be different and the result of
the function can also be different.
You will learn more about all these in the subsequent chapters.
57
8. DAX Standard Parameters DAX
DAX has standard parameter names to facilitate the usage and understanding of the
DAX functions. Further, you can use certain prefixes to the parameter names. If the prefix
is clear enough, you can use the prefix itself as the parameter name.
Any DAX expression that returns a single scalar value, where the
expression expression is to be evaluated multiple times (for each
row/context).
Any DAX expression that returns a single scalar value where the
value expression is to be evaluated exactly once before all other
operations.
58
DAX
The prefix should be in such a way that ambiguous reading of the parameter is
avoided.
For example,
For example, Consider DATE (Year_value, Month_value, Day_value). You can omit the
parameter name value, that is repeated thrice and write it as DATE (Year, Month, Day).
As you can observe, by using only the prefixes, the function is more readable.
However, sometimes the parameter name and the prefix have to be present for clarity.
For example, Consider Year_columnName. The parameter name is ColumnName and the
prefix is Year. Both are required to make the user understand that the parameter requires
a reference to the existing column of years.
59
9. DAX Functions DAX
Most of the DAX functions have the same names and functionality as that of Excel
functions. However, DAX functions have been modified to use DAX data types and to work
with tables and columns.
DAX has some additional functions that you will not find in Excel. These DAX functions are
provided for specific purposes such as lookups based on relationships associated with the
relational database aspects of the Data Model, the ability to iterate over a table to perform
recursive calculations, to perform dynamic aggregation, and for calculations utilizing time
intelligence.
In this chapter, you will learn about the functions supported in the DAX language. For
more information on the usage of these DAX functions, refer to the tutorial DAX Functions
in this tutorials library.
DAX has lookup functions that are similar to the array and vector lookup functions
in Excel.
60
DAX
You cannot use DAX functions in an Excel formula or use Excel formulas/functions
in DAX, without the required modifications.
Excel functions take a cell reference or a range of cells as reference. DAX functions
never take a cell reference or a range of cells as reference, but instead take a
column or table as reference.
Excel date and time functions return an integer that represents a date as a serial
number. DAX date and time functions return a datetime data type that is in DAX
but not in Excel.
Excel has no functions that return a table, but some functions can work with arrays.
Many of the DAX functions can easily reference complete tables and columns to
perform calculations and return a table or a column of values. This ability of DAX
adds power to the Power Pivot, Power View and Power BI, where DAX is used.
DAX lookup functions require that a relationship is established between the tables.
Excel supports variant data type in a column of data, i.e. you can have data of
different data types in a column. Whereas, DAX expects the data in a column of a
table to be always of the same data type. If the data is not of the same data type,
DAX changes the entire column to the data type that best accommodates all the
values in the column. However, if the data is imported and this issue arises, DAX
can flag an error.
To learn about DAX data types and data type casting, refer to the chapter DAX Syntax
Reference.
61
DAX
In this section, you will learn about DAX functions at the functions category level. For
details on the DAX Function Syntax and what the DAX function returns and does - refer to
the DAX Functions tutorial in this tutorials library.
DAX time intelligence functions and DAX filter functions are powerful and require a special
mention. Refer to the chapters - Understanding DAX Time Intelligence and DAX Filter
Functions for details.
Understanding DAX table valued functions helps you in writing DAX formulas effectively.
62
DAX
MAXA (<column>)
MAXX (<table>, <expression>)
MIN (<column>)
MINA (<column>)
MINX (<table>, <expression>)
PRODUCT (<column>)
PRODUCTX (<table>, <expression>)
ROW (<name>, <expression>, [<name>, <expression>] )
SELECTCOLUMNS (<table>, <name>, <scalar_expression>,
[<name>, <scalar_expression>] )
SUM (<column>)
SUMMARIZE (<table>, <groupBy_columnName>, [<groupBy_columnName>] ,
[<name>, <expression>] )
63
DAX
HASONEFILTER(<columnName>)
HASONEVALUE(<columnName>)
ISCROSSFILTERED (<columnName>)
ISFILTERED (<columnName>)
KEEPFILTERS (<expression>)
RELATED(<column>)
RELATEDTABLE(<tableName>)
SUBSTITUTEWITHINDEX (<table>, <indexColumnName>, <indexColumnsTable>,
<orderBy_expression>, [<order>], [<orderBy_expression>, [<order>]] ])
USERELATIONSHIP(<columnName1>,<columnName2>)
VALUES(<TableNameOrColumnName>)
CLOSINGBALANCEMONTH (<expression>,<dates>[,<filter>])
CLOSINGBALANCEQUARTER (<expression>,<dates>, [<filter>])
CLOSINGBALANCEYEAR (<expression>,<dates>, [<filter>], [<year_end_date>])
DATEADD (<dates>,<number_of_intervals>, <interval>)
DATESBETWEEN (<dates>,<start_date>,<end_date>)
DATESINPERIOD (<dates>,<start_date>, <number_of_intervals>,<interval>)
DATESMTD (<dates>)
DATESQTD (<dates>)
DATESYTD (<dates>, [<year_end_date>])
ENDOFMONTH (<dates>)
ENDOFQUARTER (<dates>)
ENDOFYEAR (<dates> , [<year_end_date>])
FIRSTDATE (<dates>)
FIRSTNONBLANK (<column>,<expression>)
LASTDATE (<dates>)
LASTNONBLANK (<column>,<expression>)
NEXTDAY (<dates>)
NEXTMONTH (<dates>)
NEXTQUARTER (<dates>)
NEXTYEAR (<dates>, [<year_end_date>])
64
DAX
65
DAX
ISTEXT(<value>)
USERNAME()
AND(<logical1>,<logical2>)
FALSE()
IF(logical_test>,<value_if_true>, value_if_false)
IFERROR(value, value_if_error)
NOT(<logical>)
OR(<logical1>,<logical2>)
SWITCH(<expression>, <value>, <result>, [<value>, <result>], [<else>])
TRUE()
66
DAX
ABS(<number>)
ACOS(number)
ACOSH(number)
ASIN(number)
ASINH(number)
ATAN(number)
ATANH(number)
CEILING(<number>, <significance>)
COMBIN(number, number_chosen)
COMBINA(number, number_chosen)
COS(number)
COSH(number)
CURRENCY(<value>)
DEGREES(angle)
DIVIDE(<numerator>, <denominator>, [<alternateresult>])
EVEN(number)
EXP(<number>)
FACT(<number>)
FLOOR(<number>, <significance>)
GCD(number1, [number2], ...)
INT(<number>)
ISO.CEILING(<number>, [<significance>])
LCM(number1, [number2], ...)
LN(<number>)
LOG(<number>,<base>)
LOG10(<number>)
INT(<number>)
MROUND(<number>, <multiple>)
ODD(number)
PI()
POWER(<number>, <power>)
PRODUCT(<column>)
PRODUCTX(<table>, <expression>)
67
DAX
QUOTIENT(<numerator>, <denominator>)
RADIANS(angle)
RAND()
RANDBETWEEN(<bottom>,<top>)
ROUND(<number>, <num_digits>)
ROUNDDOWN(<number>, <num_digits>)
ROUNDUP(<number>, <num_digits>)
SIN(number)
SINH(number)
SIGN(<number>)
SQRT(<number>)
SUM(<column>)
SUMX(<table>, <expression>)
TAN(number)
TANH(number)
TRUNC(<number>,<num_digits>)
EXCEPT(<table_expression1>, <table_expression2>
GROUPBY (<table>, [<groupBy_columnName1>], [<name>, <expression>] )
INTERSECT(<table_expression1>, <table_expression2>)
ISEMPTY(<table_expression>)
NATURALINNERJOIN(<leftJoinTable>, <rightJoinTable>)
NATURALLEFTOUTERJOIN(<leftJoinTable>, <rightJoinTable>)
SUMMARIZECOLUMNS (<groupBy_columnName>, [<groupBy_columnName>],
[<filterTable>] , [<name>, <expression>])
PATH(<ID_columnName>, <parent_columnName>)
68
DAX
PATHCONTAINS(<path>, <item>)
PATHITEM(<path>, <position>, [<type>])
PATHITEMREVERSE(<path>, <position>, [<type>])
PATHLENGTH(<path>)
STDEV.P(<ColumnName>)
STDEV.S(<ColumnName>)
STDEVX.P(<table>, <expression>)
STDEVX.S(<table>, <expression>)
SQRTPI(number)
VAR.P(<columnName>)
VAR.S(<columnName>)
69
DAX
VARX.P(<table>, <expression>)
VARX.S(<table>, <expression>)
XIRR(<table>, <values>, <dates>, [guess])
XNPV(<table>, <values>, <dates>, <rate>)
BLANK()
CODE(text)
CONCATENATE(<text1>, <text2>)
CONCATENATEX(<table>, <expression>, [delimiter])
EXACT(<text1>,<text2>)
FIND(<find_text>, <within_text>, [<start_num>], [<NotFoundValue>])
FIXED(<number>, <decimals>, <no_commas>)
FORMAT(<value>, <format_string>)
LEFT(<text>, <num_chars>)
LEN(<text>)
LOWER(<text>)
MID(<text>, <start_num>, <num_chars>)
REPLACE(<old_text>, <start_num>, <num_chars>, <new_text>)
REPT(<text>, <num_times>)
RIGHT(<text>, <num_chars>)
SEARCH(<find_text>, <within_text>, [<start_num>], [<NotFoundValue>])
SUBSTITUTE(<text>, <old_text>, <new_text>, <instance_num>)
TRIM(<text>)
UPPER (<text>)
VALUE(<text>)
70
10. DAX Understanding DAX Functions DAX
In Excel 2013, DAX has 246 functions. You have already learnt about the different types
of DAX functions in the chapter DAX Functions. However, if you have to use a DAX
function in a DAX formula, you need to understand the function in detail. You should know
the syntax of the function, the parameter types, what the function returns, etc.
If you are writing a DAX formula, it is suggested to use the DAX functions where applicable.
For this, you can refer to the tutorial DAX Functions in this tutorials library for an in-
depth understanding of where and how to use each of the 246 DAX functions. You can
always go back and forth between this tutorial and DAX Functions tutorial to obtain
mastery on DAX.
In this chapter, you will understand how to read and interpret the DAX functions in the
DAX Functions tutorial.
Description
Syntax
Parameters
Return Value
Remarks
Example
Description
In the Description section, you will learn what the DAX function is about and where it can
be used.
Syntax
In the Syntax section, you will learn the exact function name and the respective
parameters.
Parameters
In the Parameters section, you will learn about each of the parameters of the specific DAX
function, whether a parameter is an input or an output and if there are any options. As
seen in the chapter - DAX Standard Parameters, only the standard parameter names will
be used.
71
DAX
Return Value
In the Return Value section, you will learn about what value the DAX function will return
and its data type.
Remarks
In the Remarks section, you will learn about any extra information that you need to know
about the usage of the DAX function.
Example
The DAX function description will be ended with an example of the usage of the function.
72
11. DAX Evaluation Context DAX
In DAX, context is an important term that you should be aware of, while writing DAX
formulas. Also referred to as evaluation context, DAX context is used to determine the
evaluation of a DAX formula and the corresponding result. This means, the results of a
DAX formula can vary according to the context. You should clearly understand how a
specific DAX context is used and how the results can be different.
Evaluation context enables you to perform dynamic analysis, in which the results of a DAX
formula can change to reflect the current row or a cell selection and also any related data.
Understanding context and using context effectively are very important to build powerful
DAX formulas, perform dynamic data analysis, and troubleshoot problems in DAX
formulas. Evaluation contexts are the basis of all of the advanced features of DAX that you
need to master to create complex data analysis reports.
As you keep referencing to DAX functions for relevant usage in DAX formulas, you need
to refer to this chapter on DAX context to obtain clarity on the results.
Row Context
Filter Context
When a DAX formula is evaluated, all the contexts will be taken into account and are
applied as relevant. The contexts exist together and the result of the formula will be
different based on the context that is used while calculating a value. For example, when
you select fields for rows, columns, and filters in a PivotTable, the subtotals are
dynamically calculated based on which row and which column the subtotal/total is
associated with and the values in the rows and columns are determined by the filters used.
Row Context
Row context means that the DAX formula or the DAX function knows which row of the
table it is referencing at any point in time. You can consider row context as the current
row. The formula will get calculated row-by-row with the row context.
Some DAX functions (e.g., the X-functions, FILTER ()) and all calculated columns have a
row context. For example, if you create a calculated column Year with the DAX formula
=YEAR ([Date]), the values of the calculated column are obtained by applying the given
DAX formula on the given column in the table, row by row.
This means that if you have created a calculated column, the row context consists of the
values in each individual row and the values in the columns that are related to the current
row, as determined by the DAX formula used. Though the DAX formula does not contain
the reference to a row, DAX implicitly understands the row context while calculating
values.
73
DAX
DAX creates a row context automatically when you define a calculated column and all the
calculated values with the DAX formula used will appear in the calculated column.
In contrast, when you have a DAX function such as SUMX, the values calculated row by
row get summed up and only the final result will be displayed. That is, the intermediate
values are discarded.
When you have related tables, the row context determines which rows in the related table
are associated with the current row. However, the row context does not propagate through
relationships automatically. You have to use the DAX functions - RELATED and
RELATEDTABLE for this.
For example, you can use the DAX function Earlier () that stores the row context from the
operation that preceded the current operation. This function stores two sets of context in
memory - one set of context represents the current row for the inner loop of the formula,
and another set of context represents the current row for the outer loop of the formula.
DAX automatically feeds the values between the two loops so that you can create complex
aggregates.
For an example, refer to the scenario - Creating a DAX Formula that Dynamically Ranks
Values in the chapter Scenarios - Ranking and Comparing Values.
Filter Context
Filter context refers to any filtering that is applied to the Data Model in DAX. Filter context
is created by a PivotTable and also by the DAX functions.
Rows
Columns
Filters
Slicers
The filter context created by a PivotTable, filters the underlying tables in the Data Model.
If the tables are related, then the filters flow down from the lookup tables to data tables.
That means, you can filter the data tables based on the results from the lookup tables.
The filter propagation does not happen the other way round. However, you can use DAX
formulas to filter the lookup tables based on the results from the data tables.
74
DAX
75
12. DAX Formulas DAX
DAX is a formula language for creating custom calculations in Power PivotTables. You can
use the DAX functions that are designed to work with relational data and perform dynamic
aggregation in DAX formulas.
DAX formulas are very similar to Excel formulas. To create a DAX formula, you type an
equal sign, followed by a function name or expression and any required values or
arguments.
A DAX function always reference a complete column or a table. If you want to use
only particular values from a table or column, you can add filters to the formula.
If you want to customize calculations on a row by row basis, Power Pivot provides
functions that let you use the current row value or a related value to perform
calculations that vary by context.
DAX includes a type of function that returns a table as its result, rather than a
single value. These functions can be used to provide input to other functions, thus
calculating values for entire tables or columns.
Some DAX functions provide time intelligence, which lets you create calculations
using meaningful ranges of dates and compare the results across parallel periods.
To the right of the equal sign, you can either type or select a function name, or
type an expression. The expression can contain table names and column names
connected by DAX operators.
[column_Cost] + [column_Tax]
=Today ()
76
DAX
Begin to type the first few letters of the function name. AutoComplete displays a
list of available functions with the names beginning with those letters.
Place the pointer on any of the function names. IntelliSense tooltip will be displayed
giving you the use of the function.
Click the function name. The function name appears in the formula bar and the
syntax is displayed, which will guide you as you select the arguments.
Type the first letter of the table name that you want. AutoComplete displays a list
of available tables and columns with the names beginning with that letter.
Press TAB or click the name to add an item from the AutoComplete list to the
formula.
Click the Fx button to display a list of available functions. To select a function from
the dropdown list, use the arrow keys to highlight the item and click OK to add the
function to the formula.
Supply the arguments to the function by selecting them from a dropdown list of
possible tables and columns or by typing in required values.
You can use DAX formulas in calculated columns, by adding a column and then
typing an expression in the formula bar. You create these formulas in the
PowerPivot window.
You can use DAX formulas in calculated fields. You create these formulas
In a calculated column, the formula is always applied to every row in the column,
throughout the table. Depending on the row context, the value might change.
77
DAX
It is important to understand the concept of context in DAX to write DAX formulas. This
can be a bit difficult in the beginning of your DAX journey, but once you get a grasp on it,
you can write effective DAX formulas that are required for complex and dynamic data
analysis. For details, refer to the chapter DAX Context.
o If you have chosen the table name, type bracket [. Type the first letter of
the column name and select the complete name from the dropdown list.
For example, you want to find the total sales amount in the East region. You can write a
DAX formula as shown below. East_Sales is the name of the table. Amount is a column in
the table.
SUM ([East_Sales[Amount])
The DAX formula can vary based on whether it is for a calculated field or calculated column.
Refer to the sections below for details.
78
DAX
Click the tab of the table in which you want to add the calculated column.
Click the Design tab on the Ribbon.
Click Add.
Type the DAX formula for the calculated column in the formula bar.
This DAX formula does the following for every row in the table East_Sales:
Divides the value in Amount column of a row by the value in Units column in the
same row.
Places the result in the new added column in the same row.
Repeats steps 1 and 2 iteratively till it completes all the rows in the table.
You have added a column for Unit Price at which those units are sold with the above
formula.
As you can observe, calculated columns require computation and storage space as
well. Hence, use calculated columns only if necessary. Use calculated fields where
possible and sufficient.
To create a DAX formula for a calculated field in the Excel window, use the
Calculated Field dialog box.
To create a DAX formula for a calculated field in the Power Pivot window, click a
cell in the calculation area in the relevant table. Start the DAX formula with
CalculatedFieldName:=.
If you use Calculated Field dialog box in the Excel window, you can check the formula
before you save it and make it as a mandatory habit to ensure the use of correct formulas.
For more details on these options, refer to the chapter Calculated Fields.
79
DAX
To enter the name of a table, begin typing the name of the table. Formula
AutoComplete provides a dropdown list containing valid table names that begin
with those letters. You can start with one letter and type more letters to narrow
down the list if required.
To enter the name of a column, you can select it from the list of column names in
the selected table. Type a bracket [, to the right of the table name, and then
choose the column from the list of columns in the selected table.
You can nest functions and formulas in a DAX formula. In such a case, you can use
Formula AutoComplete in the middle of an existing formula with nested functions.
The text immediately before the insertion point is used to display values in the
dropdown list and all of the text after the insertion point remains unchanged.
Defined names that you create for constants do not get displayed in the
AutoComplete dropdown list, but you can still type them.
The Insert Function button in the Power Pivot window is to the left of formula bar.
The Insert Function button in the Excel window is in the Calculated Field dialog box
to the right of Formula.
When you click on the fx button, Insert Function dialog box appears. The Insert Function
dialog box is the easiest way to find a DAX function that is relevant to your DAX formula.
80
DAX
The Insert Function dialog box helps you select functions by category and provides short
descriptions for each function.
You can use Insert Function dialog box using the following steps
Medal Count:=
Select Statistical in the Select a category box as shown in the following screenshot.
Select COUNTA in the Select a function box as shown in the following screenshot.
81
DAX
As you can observe, the selected DAX function syntax and the function description are
displayed. This enables you to make sure that it is the function that you want to insert.
Click OK. Medal Count:=COUNTA( appears in the formula bar and a tooltip
displaying the function syntax also appears.
Type [. This means you are about to type a column name. The names of all the
columns and the calculated fields in the current table will be displayed in the
dropdown list. You can use IntelliSense to complete the formula.
Type M. The displayed names in the dropdown list will be limited to those starting
with M.
Click Medal.
82
DAX
Press Enter. You are done. You can use the same procedure to create a calculated
column also. You can also follow the same steps to insert a function in the
Calculated Field dialog box in the Excel window using the Insert Function feature.
Insert Function dialog box appears. The rest of the steps are the same as above.
If a DAX formula has many nested functions, it has the following disadvantages:
In such cases, you can split the formula into smaller manageable formulas and build the
large formula incrementally.
83
DAX
You can automatically create formulas using standard aggregations by using the AutoSum
feature in the Power Pivot window.
Click the Results tab in the Power Pivot window. Results table will be displayed.
Click the Medal column. The entire column Medal will be selected.
Click the Home tab on the Ribbon.
Click the down arrow next to AutoSum in the Calculations group.
84
DAX
As you can observe, the calculated field Count of Medal appears in the calculation area
below the column Medal. The DAX formula also appears in the formula bar -
Count of Medal:=COUNTA([Medal])
The AutoSum feature has done the work for you created the calculated field for data
aggregation. Further, AutoSum has taken the appropriate variant of the DAX function
COUNT, i.e. COUNTA (DAX has COUNT, COUNTA, COUNTAX functions).
A word of caution To use AutoSum feature, you need to click the down arrow next to
AutoSum on the Ribbon. If you click on the AutoSum itself instead, you will get
Sum of Medal:=SUM([Medal])
And an error is flagged as Medal is not a numeric data column and the text in the column
cannot be converted to numbers.
85
DAX
You can refer to the chapter - DAX Error Reference for details on DAX errors.
When you create a relationship between two tables, you are expected to make sure that
the two columns used as keys have values that match, at least for most of the rows, if not
completely. In the Power Pivot Data Model, it is possible to have non-matching values in
a key column and still create a relationship, because Power Pivot does not enforce
referential integrity (look at the next section for details). However, the presence of blank
or non-matching values in a key column might affect the results of the DAX formulas and
the appearance of PivotTables.
86
DAX
Referential Integrity
Establishing referential integrity involves building a set of rules to preserve the defined
relationships between tables when you enter or delete data. If you do not exclusively
ensure this, as Power Pivot does not enforce it, you might not get correct results with the
DAX formulas created before data changes are made.
If you enforce referential integrity, you can prevent the following pitfalls:
Adding rows to a related table when there is no associated row in the primary table
(i.e. with matching values in the key columns).
Changing data in a primary table that would result in orphan rows in a related table
(i.e. rows with a data value in the key column that does not have a matching value
in the primary table key column).
Deleting rows from a primary table when there are matching data values in the
rows of the related table.
87
13. DAX Updating the Results of DAX Formulas
DAX
DAX formulas are used in calculations involving large data, including data from external
data sources. The data can be subjected to changes from time to time as the DAX
calculations are meant for live data as well.
Data refresh is the process of updating the data in the Data Model in your workbook
obtaining up-to-date data from external data sources.
Recalculation is the process of updating all the columns, tables, and PivotTables in
your workbook that contain DAX formulas, to reflect the changes in the underlying
data that result from the changes to DAX formulas themselves.
You should not save or publish the workbook until the DAX formulas in it have been
recalculated.
You can refresh data manually from the Power Pivot window at intervals that you
can specify.
You can schedule an automatic data refresh from external sources, if you have
published the workbook to a SharePoint site.
For details on these, refer to the chapter Updating Data in Data Model.
88
DAX
For a calculated column, the result of DAX formula should always be recalculated
for the entire column, whenever you change the DAX formula.
For a calculated field, the result of DAX formula is not calculated until the calculated
field is placed in the context of a PivotTable or a PivotChart. The DAX formula will
be recalculated when you change any row or column heading that affects the filters
on the data or when you manually refresh the PivotTable.
To learn more about recalculation, refer to the chapter Recalculating DAX Formulas.
89
14. DAX Updating Data in the Data Model DAX
DAX is used for calculations on the data in the Data Model in Excel Power Pivot. DAX
enables data modeling and reporting activities to be handled in an effective way. However,
this requires updating the data in the Data Model from time to time so as to reflect the
current data.
You can import data from an external data source into the Data Model of your workbook
by establishing a data connection. You can update the data from the source whenever you
choose. This option is handy if you are getting data from relational databases that contain
live sales information or data feeds that are updated several times a day.
Note that addition of data, changing data, or editing filters always triggers recalculation of
DAX formulas that depend on that data source. Refer to the chapter Recalculating DAX
Formulas for details.
Manual Refresh
If you choose manual refresh option, you can refresh the data in the Data Model manually
at any time. You can refresh all data, which is the default, or you can manually choose the
tables and columns to refresh for individual data sources.
90
DAX
If you have imported data from a relational data source, such as SQL Server and Oracle,
you can update all the related tables in one operation. The operation of loading new or
updated data into the Data Model often triggers recalculation of DAX formulas, both of
which might require some time to complete. Hence, you should be aware of the potential
impact before you change data sources or refresh the data that is obtained from the data
source.
To refresh data for a single table or all tables in a Data Model, do the following
Click the Home tab on the Ribbon in the Power Pivot window.
Click Refresh.
Click Refresh in the dropdown list for refreshing the selected table.
Click Refresh All in the dropdown list for refreshing all the tables.
To refresh data for all tables that use the same connection in a Data Model, do the
following:
91
DAX
Select a connection.
Click the Refresh button.
Data Refresh dialog box appears and data refresh progress information is displayed as the
PowerPivot engine reloads data from the selected table or from all tables from the data
source.
Error An error can occur if the database is offline, you no longer have
permissions. A table or column is deleted or renamed in the source.
Cancelled This means Excel did not issue the refresh request, probably
because refresh is disabled on the connection.
92
DAX
You can make the following changes to the existing data sources -
Connections
Edit the database name or the server name.
Change the name of the source text file, spreadsheet, or data feed.
Change the location of the data source.
For relational data sources, change the default catalog or initial catalog.
Change the authentication method or the credentials used to access the data.
Edit advanced properties on the data source.
93
DAX
Tables
Add or remove a filter on the data.
Change the filter criteria.
Add or remove tables.
Change the table names.
Edit mappings between tables in the data source and tables in the Data Model.
Select different columns from the data source.
Columns
Change the column names.
Add new columns.
Delete columns from the Data Model (does not affect the data source).
You can edit the properties of an existing data source in the following ways:
You can change the connection information, including the file, feed, or database
used as a source, its properties or other provider specific connection options.
You can change the table and column mappings and remove references to columns
that are no longer used.
You can change the tables, views, or columns that you get from the external data
source.
94
DAX
Existing Connections dialog box appears. Select the connection that you want to modify.
Depending on the type of the data source you are changing, the provider might be
different. Also the properties that are available may require change. Consider a simple
example of a connection to an Excel workbook that contains the data.
95
DAX
Click the Browse button to locate another database of the same type (Excel
workbook in this example), but with a different name or location.
The new file will get selected. A message appears stating that you have modified
connection information and you need to save and refresh the tables to verify the
connection.
Click the Save button. You will be back in the Existing Connections dialog box.
Click the Refresh button. Data Refresh dialog box appears displaying the data
refresh progress. The status of data refresh will be displayed. Refer to the section
- Manually Refreshing an Existing Data Source for details.
Click the tab that contains the table you want to modify in the Power Pivot window.
96
DAX
97
DAX
The name of the selected table in the Data Model is displayed in the Table
Name box.
The name of the corresponding table in the external data source is displayed in
the Source Name box.
There are two options for column names from Source and Modal.
If the columns are named differently in the data source and in the Data Model, you
can toggle between the two sets of column names by selecting these options.
To change the table that is used as a data source, select a different table than the
selected one in the Source Name dropdown list.
o To add a column that is present in the source but not in the Data Model, select
the checkbox beside the column name. Repeat for all the columns that are to
be added. The actual data will be loaded into the Data Model, the next time
you refresh.
o If some columns in the Data Model are no longer available in the current data
source, a message appears in the notification area that lists the invalid
columns. You do not need to do anything.
When you save the current set of table properties, you will get a message Please wait.
Then the number of rows retrieved will be displayed.
In the table in the Data Model, any invalid columns are automatically removed and new
columns are added.
Double-click on the header of the column. The name of the column in the header
will get highlighted.
Type the new column name, overwriting the old name. Alternatively, you can
change the name of a column in a table in the Data Model as follows:
98
DAX
The name of the column in the header will get highlighted. Type the new column name,
overwriting the old name.
As you have learnt, all the values in a column in a table in the Data Model must be of the
same data type.
Select the column that you want to change by clicking its header.
Click the controls in the Formatting group to modify the column's data type and
format.
99
DAX
100
DAX
In the list of column values, select or clear one or more values to filter by and then
click OK.
However, if the number of values is extremely large, individual items might not be
shown in the list. Instead, you will see the message - "Too many items to show."
Click Number Filters or Text Filters (depending on the data type of the column).
Note: If you make a mistake at any stage, click the Clear Row Filters button and start
over.
Click OK. You will be back to Select Tables and Views page of Table Import Wizard.
101
DAX
As you can observe, in the column Filter Details, a link Applied Filters appears for the
column on which you defined the filter.
You can click the link to view the filter expression that was built by the wizard. But, the
syntax for each filter expression depends on the provider and you cannot edit it.
102
DAX
Click the connection that contains the table on which you have to change the filter.
Click the Open button.
You will get into Table Import Wizard dialog box. Repeat the steps in the previous section
to filter the columns.
103
15. DAX Recalculating DAX Formulas DAX
Recalculation of a DAX formula is required to reflect changes in the data and changes
in the formula itself. However, recalculating a DAX formula involves performance cost.
Types of Recalculation
You have two options for recalculating DAX formulas
By default, Power Pivot automatically recalculates as required while optimizing the time
required for processing. However, you can choose to update calculations manually, if you
are working with complex formulas or very large data sets and want to control the timing
of updates.
Both automatic and manual modes of recalculating DAX formulas have advantages.
However, the recommended way is to use automatic recalculation mode. This way you can
keep the Power Pivot data in sync and prevent problems caused by deletion of data,
changes in names or data types or missing dependencies.
Names of tables or columns that are referenced in the DAX formula have been
changed.
Changes have been made to other DAX formulas within the workbook, so columns
or calculations that depend on those DAX formulas need to be recalculated.
104
DAX
You applied a filter that requires execution of a query to update the data set. The
filter could have been applied either in a DAX formula or as part of a PivotTable or
PivotChart.
You can use manual recalculation of DAX formulas in the following conditions:
You are designing a DAX formula by using a template and want to change the
names of the columns and tables used in the DAX formula before you validate it.
You know that some data in the workbook has changed but you are working with
a different column that has not changed so you want to postpone a recalculation.
You are working in a workbook that has many dependencies and want to defer
recalculation till you are sure that all the necessary changes have been made.
But, you should be aware that as long as the workbook is configured to manual
recalculation mode, any validation or checking of formulas is not performed. This will result
in the following
Any new formulas that you add to the workbook will be flagged as containing an
error.
Click the Design tab on the Ribbon in the Power Pivot window.
Click the Calculation Options in the Calculations group.
Click the Manual Calculation Mode in the dropdown list.
105
DAX
Click the Design tab on the Ribbon in the Power Pivot window.
Click the Calculation Options field in the Calculations group.
Click the Calculate Now field in the dropdown list.
106
16. DAX Troubleshooting DAX Formula Recalculation
DAX
Whenever changes occur in the Data Model of your workbook, Power Pivot performs an
analysis of the existing data to determine whether recalculation is required and performs
the update in the most efficient way possible.
Dependencies
Sequence of recalculation for dependent columns
Transactions
Recalculation of volatile functions
Dependencies
When a column depends on another column, and the contents of that other column change
in any way, all related columns might need to be recalculated.
Power Pivot always performs a complete recalculation for a table, because a complete
recalculation is more efficient than checking for changed values. The changes that trigger
recalculation might include deleting a column, changing the numeric data type of a column
or adding a new column. These changes are considered as major changes. However,
seemingly trivial changes, such as changing the name of a column might also trigger
recalculation. This is because the names of the columns are used as identifiers in the DAX
formulas.
In some cases, Power Pivot may determine that columns can be excluded from
recalculation.
Transactions
Operations that recalculate or refresh data take place as a transaction. This means that if
any part of the refresh operation fails, the remaining operations are rolled back. This is to
ensure that data is not left in a partially processed state. However, you cannot manage
the transactions as you do in a relational database or create checkpoints.
107
DAX
The results for these DAX functions are only recalculated when the entire column is
recalculated. These situations include refresh from an external data source or manual
editing of data that causes re-evaluation of DAX formulas that contain these functions.
However, such functions will always be recalculated if the functions are used in the
definition of a Calculated Field.
108
17. DAX Formula Errors DAX
You can get errors when you write DAX formulas with wrong syntax. Calculated fields
and calculated columns can contain DAX functions that require a specific type of
arguments. Arguments of DAX functions can be tables, columns, or other DAX functions
(nested DAX functions). As DAX functions can return tables and columns, care should be
taken to check that the right type of arguments are passed to the DAX functions.
DAX formula errors can be either syntax errors or semantic errors. The errors can occur
either at design time or at run time.
In this chapter, you will learn about some common DAX errors, their causes, and how to
fix those errors.
Cause at Run-time
This error can be displayed when a calculated field with a DAX time intelligence function
is placed in the VALUES area of a PivotTable and date fields such as the month or the
quarter are selected as slicers or filters before selecting a year. For example, if you have
data of three years 2014, 2015, and 2016 and you try to use only the month March
without selecting the Year field, then the values are not contiguous data values and you
will get an error.
Then, select one or more months or quarters to slice or filter on for the year
selected.
109
DAX
Cause at Design-time
DAX time intelligence functions require a date column specified for the date argument.
The date column must have a contiguous range of dates. This error can be returned, if
there is a date value in one or more rows in the date column that is not contiguous with
the data values in the previous and successive rows.
If you imported your table containing dates from a data source, remember that many
organizations run special processes that scan tables in databases for invalid values and
replace those with a particular value. That is, if an invalid date is found, it is assigned a
particular date value that may not be contiguous with other data values in the column.
If your date table is imported from a data source, use Refresh in Power Pivot
window to reimport any changes found at the source.
Check the values in your date column to make sure they are in a contiguous order.
If any value is found not to be in place, it will have to be corrected at the source
and the date table will have to be refreshed.
Create a separate date table and date column in your Data Model. Specify the new
date column as the date argument in the formula causing the error. Date tables
are easy to create and add to a Data Model.
A function CALCULATE has been used in a true-false expression that is used as a table
filter expression. This is not allowed.
Cause
This error can appear when one or more filter expressions cannot be used in context of
the calculated field or calculated column expression.
In most of the cases, this error is caused by a filter expression specified as an argument
to the DAX CALCULATE function. The CALCULATE function requires filters defined as a
Boolean expression or a table expression.
110
18. DAX Time Intelligence DAX
DAX has an important and powerful feature, referred to as Time Intelligence. Time
intelligence enables you to write DAX formulas that refer to the time periods for use in the
PivotTables.
DAX has 35 time-intelligence functions specifically for aggregating and comparing data
over time. However, these DAX functions have some constraints on the data that you need
to understand and work with caution to avoid errors.
For example, you might want to sum sales amounts for the past month product-wise and
compare the totals with those of other months in the fiscal year. This means, you have to
use the dates as a way to group and aggregate sales transactions for a particular period
in time.
This is where you can observe the power of DAX. You can use DAX time intelligence
functions to define calculated fields that help you in analyzing the data over time, without
having to change the date selections in the pivot tables. This makes your job easier.
Moreover, you can build PivotTables that would not be possible any other way.
The date table must include a column considered to be the Date column by DAX.
You can name the column the way you want, but it should comply with the following
conditions:
o The date column should contain a contiguous set of dates that covers every
day in the time period you are analyzing the data.
o Every date must exist once and only once in the date column.
o You cannot skip any dates (For e.g. you cannot skip weekend dates).
111
DAX
DAX time intelligence functions work only on a standard calendar and assume the
start of the year as January 1 and the end of the year as December 31, with the
months in the year and days in each month as of a calendar year.
However, you can customize a standard calendar for different financial years. It is a good
practice to verify the above requirements before any time intelligence function is used.
For more details on date tables and their usage in DAX formulas, refer to the tutorial =
Data Modeling with DAX in this tutorials library.
112
DAX
There are 16 DAX functions in this category. Eight (8) of these DAX functions are the
previous and next functions.
The previous and next functions start with a date column in the current context
and calculate the previous or next day, month, quarter or year.
The previous functions work backward from the first date in the current context
and the next functions move forward from the last date in the current context.
The previous and next functions return the resulting dates in the form of a
single column table.
113
DAX
Four (4) DAX functions calculate a set of dates in a period. These functions perform the
calculations using the last date in the current context.
114
DAX
Four (4) DAX functions are used to shift from the set of dates that are in the current
context to a new set of dates.
These DAX functions are more powerful than the previous ones.
For example:
115
DAX
Three (3) DAX functions in this category can be used to evaluate any given
expression over a specified time period.
Six (6) DAX functions in this category can be used to calculate the opening and the
closing balances.
o The opening balance for any period is the same as the closing balance for
the previous period.
o The closing balance includes all data through the end of the period, while
the opening balance does not include any data from within the current
period.
o These DAX functions always return the value of an expression evaluated for
a specific point in time.
The point in time we care about is always the last possible date value in a calendar
period.
The opening balance is based on the last date of the previous period, while the
closing balance is based on the last date in the current period.
The current period is always determined by the last date in the current date
context.
116
DAX
117
19. DAX Filter Functions DAX
DAX has powerful filter functions that are quite different from Excel functions. The lookup
functions work by using tables and relationships, like a database. The filtering functions
let you manipulate data context to create dynamic calculations.
Note: DAX filter functions that return a table do not add the table to the Data Model. The
resulting table is used as an argument in another DAX function. That is, such DAX functions
are used as nested functions with other DAX functions.
In the next section, you will learn what DAX filter functions you can use. For more details
on these functions, refer to the tutorial DAX Functions in this tutorials library.
118
DAX
119
DAX
120
DAX
121
20. DAX Scenarios DAX
You have learnt DAX syntax, the usage of DAX operators and DAX functions in the previous
chapters. As you are aware, DAX is a formula language used for data modeling and data
analysis.
DAX can be used in various scenarios. Based on the DAX scenarios, DAX optimizes the
performance and produces accurate and effective results. In this chapter, you will get to
know some of the DAX scenarios.
For details, refer to the chapter Scenarios - Working with Text and Dates.
122
DAX
For details, refer to the chapter Scenarios - Conditional Values and Testing for Errors.
DAX time intelligence functions include functions to help you retrieve dates or date ranges
from your data. You can then use those dates or date ranges to calculate values across
similar periods. The time intelligence functions also include functions that work with
standard date intervals, to allow you to compare values across months, years, or quarters.
You could also create a DAX formula that compares values for the first and the last date
of a specified period.
You can learn more about DAX intelligence functions and what they can do for the
following:
For details, refer to the chapter Scenarios - Ranking and Comparing Values.
123
21. DAX Scenarios Performing Complex Calculations
DAX
DAX formulas can perform complex calculations that involve custom aggregations,
filtering, and the use of conditional values. You can do the following with DAX
CALCULATE Function
CALCULATE (<expression>, [<filter1>], [<filter2>])
CALCULATE function evaluates the given expression in a context that is modified by zero
or more specified filters.
If your data has been filtered, the CALCULATE function changes the context in which the
data is filtered and evaluates the expression in the new context that you specify by the
filters. That means, any existing filters on the specified column are removed and the filter
used in the filter argument is applied instead.
Example
Suppose you want to display the percentage of medals sport-wise filtered by Country
names. Your calculation should get the percentage value overriding the filter that you
apply on Country in the PivotTable.
124
DAX
With this DAX formula, all the rows in the Results table are taken into account in the
CALCULATE function with the filter containing the ALL function. This way, you have the
total count in the denominator.
125
DAX
In the above screenshot, Country is filtered to USA and Top 18 values are displayed in the
PivotTable. Next, you can dynamically filter values in the PivotTable. However, the
calculations will be correct by the custom DAX formula that you used.
The CALCULATETABLE function takes a table of values and performs the same action as
that of CALCULATE function.
The filter expression enables you to obtain a subset of the source data. The filter is applied
dynamically each time that you update the results of the DAX formula, depending on the
current context of your data and you can be assured of accurate and expected results.
The filter expression typically contains a DAX filter function that returns only selected rows
of the table, which then can be used as an argument for another DAX function that you
are using for data aggregation.
126
DAX
Example
The following screenshot shows the definition of a calculated field that gives medal count
only for summer sports.
With this calculated field, the PivotTable looks as shown in the following screenshot.
127
DAX
As you can observe, the values in the PivotTable on the right side with the new calculated
field match with those that are in the PivotTable on the left side with the filter on Season
field applied explicitly.
Note: DAX filter and value functions return a table, but never return the table or rows
directly to the Data Model and hence are always embedded in another DAX function.
For details on these DAX functions, refer to the chapter DAX Filter Functions.
Additionally, you can use the DAX functions DISTINCT and VALUES for returning distinct
values.
128
22. DAX Scenarios Working with Text and Dates
DAX
DAX can be used in the scenarios involving working along with text, extracting and
composing date and time values or creating values based on a condition. You can do the
following with DAX
You can use the DAX function CONCATENATE to combine two columns into a single column
in a table in the Data Model. DAX function CONCATENATE joins two text strings into one
text string. The joined items can be text, numbers, or Boolean values represented as text
or a combination of those items. You can also use a column reference if the column
contains appropriate values.
DAX CONCATENATE function accepts only two arguments. If any of the arguments is not
of text data type, it will be converted to text. DAX CONCATENATE function returns the
concatenated string.
If your data source contains dates of a different format, you need to first extract the date
parts using a DAX formula and combine those parts to constitute a valid DAX datetime
data type.
129
DAX
You can use the following DAX functions to extract and compose dates
You can either use pre-defined Date and Time formats or you can create user-defined Date
and Time formats for the argument format_string of the FORMAT function.
Following are the predefined date and time format names. If you use strings other than
these predefined strings, they will be interpreted as a custom date and time format.
Format_String Description
130
DAX
Alternatively, you can use the characters in the following table to create user-defined
date/time formats.
Character Description
Time separator.
: Separates hours, minutes, and seconds when time values are
formatted.
Date separator.
/ Separates the day, month, and year when date values are
formatted.
%d: Displays the day as a number without a leading zero (e.g. 5).
%dd: Displays the day as a number with a leading zero (e.g. 05).
%M: Displays the month as a number without a leading zero (e.g. January is
represented as 1).
%MM: Displays the month as a number with a leading zero (e.g. January is
represented as 01).
%h: Displays the hour as a number without leading zeros using the 12-hour clock
(e.g. 1:15:15 PM). Use %h if this is the only character in your user-defined numeric
format.
%hh: Displays the hour as a number with leading zeros using the 12-hour clock
(e.g. 01:15:15 PM).
131
DAX
%H: Displays the hour as a number without leading zeros using the 24-hour clock
(e.g. 13:15:15, 1:15:15). Use %H if this is the only character in your user-defined
numeric format.
%HH: Displays the hour as a number with leading zeros using the 24-hour clock
(e.g. 13:15:15, 1:15:15).
%m: Displays the minute as a number without leading zeros (e.g. 2:1:15). Use
%m if this is the only character in your user-defined numeric format.
%mm: Displays the minute as a number with leading zeros (e.g. 2:01:15).
%s: Displays the second as a number without leading zeros (e.g. 2:15:5). Use %s
if this is the only character in your user-defined numeric format.
%ss: Displays the second as a number with leading zeros (e.g. 2:15:05).
%t: Uses the 12-hour clock and displays an uppercase A for any hour before noon;
displays an uppercase P for any hour between noon and 11:59 P.M. Use %t if this
is the only character in your user-defined numeric format.
%tt: For locales that use a 12-hour clock, displays an uppercase AM with any hour
before noon; displays an uppercase PM with any hour between noon and 11:59
P.M. For locales that use a 24-hour clock, displays nothing.
%y: Displays the year number (0-9) without leading zeros. Use %y if this is the
only character in your user-defined numeric format.
%yy: Displays the year in two-digit numeric format with a leading zero, if
applicable.
%z: Displays the timezone offset without a leading zero (e.g. -8). Use %z if this
is the only character in your user-defined numeric format.
%zz: Displays the timezone offset with a leading zero (e.g. -08)
As you can observe, formatting strings are case sensitive. Different formatting can be
obtained by using a different case.
132
DAX
You have already learnt about using Format function for converting dates to strings.
133
DAX
134
23. DAX Scenarios Conditional Values & TestingDAXfor
Errors
You can use DAX functions to test the values in the data that result in different values
based on a condition. For e.g., you can test the yearly sales amount and based on the
result, label resellers either as Preferred or Value.
You can also use DAX functions for checking the range or the type of values, to prevent
unexpected data errors from breaking calculations.
CONCATENATE (<text1>, <text2>) - Joins two text strings into one text string. The
joined items can be text, numbers, or Boolean values represented as text or a combination
of those items. You can also use a column reference, if the column contains appropriate
values.
Division by zero.
Argument to a function is blank while the expected argument is numeric value.
You can use a combination of logical and information functions to test for errors and always
return valid values to avoid returning errors in a calculated column. Following DAX
functions help you in this.
ISBLANK (<value>) - Checks whether a value is blank and returns TRUE or FALSE.
Both the return value of the expression and value_if_error must be of same data type.
Otherwise, you will get an error.
135
24. DAX Scenarios Using Time Intelligence DAX
You have learnt about the DAX powerful feature Time Intelligence in the chapter
Understanding Time Intelligence. In this chapter, you will learn how to use DAX time
intelligence functions in various scenarios.
Functions that help you retrieve dates or date ranges from your data, which are
used to calculate values across similar periods.
Functions that work with standard date intervals, to allow you to compare values
across months, years, or quarters.
Functions that retrieve the first and last date of a specified period.
Functions that help you work on the opening and closing balances.
136
DAX
You can create the following calculated fields for the product inventory at a specified time
by using the following DAX functions
You can use the following DAX time intelligence functions to compare the sums across
different time periods.
137
DAX
You can create the following calculated fields for calculating sum of sales in the West region
at the specified time periods for comparison, by using the DAX functions
This DAX function returns a table that contains a column of dates representing a period
parallel to the dates in the specified dates column, in the current context, with the dates
shifted a number of intervals either forward or backward in time.
You can create the following calculated field for calculating the previous years sales in
West region
138
DAX
You can create the following calculated fields for calculating running sum of sales in the
West region at specified time periods, by using the DAX functions
FIRSTDATE (<dates>) - Returns the first date in the current context for the specified
column of dates.
LASTDATE (<dates>) - Returns the last date in the current context for the specified
column of dates.
You can create the following DAX formulas for calculating the sum of sales in the West
region over a specified date range, by using the DAX functions
DAX Formula to calculate the sales for the 15 days prior to July 17, 2016.
CALCULATE (
SUM (WestSales[SalesAmount]), DATESINPERIOD (DateTime[DateKey],
DATE(2016,17,14), -15, day))
DAX Formula to create a calculated field that calculates the first quarter 2016 sales.
DAX Formula to create a calculated field that obtains the first date when a sale was
made in the West region for the current context.
139
DAX
DAX Formula to create a calculated field that obtains the last date when a sale was
made in the West region for the current context.
DAX Formula to calculate the dates that are one year before the dates in the current
context.
=DATEADD (DateTime[DateKey],-1,year)
140
25. DAX Scenarios Ranking and Comparing Values
DAX
If you want to show only the top n number of items in a column or PivotTable, you have
the following two options:
You can create a DAX formula that dynamically ranks values and then uses the
ranking values in a Slicer.
Click the down arrow in the row labels heading in the PivotTable.
Click the Value Filters in the dropdown list and then click Top 10.
Under Show, select the following in the boxes from left to right.
o Top
o 18 (The number of top values that you want to display. The default is 10.)
o Items.
o In the by box, select Medal Count.
141
DAX
Advantages
It is simple and easy to use.
Suitable for tables with large number of rows.
Disadvantages
The filter is solely for display purposes.
If the data underlying the PivotTable changes, you must manually refresh the
PivotTable to see the changes.
You can obtain a rank value for a given value in a row by counting the number of rows in
the same table having a value larger than the one that is being compared. This method
returns the following
Equal values will have the same rank value. If n number of values are equal, the
next value after the equal values will have a nonconsecutive rank value adding up
the number n.
For example, if you have a table Sales with sales data, you can create a calculated column
with the ranks of the Sales Amount values as follows -
Next, you can insert a Slicer on the new calculated column and selectively display the
values by ranks.
142
DAX
Advantages
The ranking is done in the table and not on a PivotTable. Hence, can be used in any
number of PivotTables.
DAX formulas are calculated dynamically. Hence, you can always be sure that the
ranking is correct even if the underlying data has changed.
Since the DAX formula is used in a calculated column, you can use the ranking in
a Slicer.
Disadvantages
Since the DAX calculations are computationally expensive, this method might not be
suitable for tables with large number of rows.
143