Data Analysis Expressions - DAX - Reference (1) (001-318) (100-200)
Data Analysis Expressions - DAX - Reference (1) (001-318) (100-200)
TODAY()
Return Value
A date (datetime).
Remarks
The TODAY function is useful when you need to have the current date displayed on a
worksheet, regardless of when you open the workbook. It is also useful for calculating
intervals.
Note
If the TODAY function does not update the date when you expect it to, you might
need to change the settings that control when the column or workbook is
refreshed. For more information, see Data Refresh.
The NOW function is similar but returns the exact time, whereas TODAY returns the time
value 12:00:00 PM for all dates.
Example
Description
If you know that someone was born in 1963, you might use the following formula to find
that person's age as of this year's birthday:
Code
=YEAR(TODAY())-1963
Comments
This formula uses the TODAY function as an argument for the YEAR function to obtain
the current year, and then subtracts 1963, returning the person's age.
See Also
Date and Time functions
NOW
WEEKDAY Function
Returns a number from 1 to 7 identifying the day of the week of a date. By default the
day ranges from 1 (Sunday) to 7 (Saturday).
Syntax
WEEKDAY(<date>, <return_type>)
99
Parameters
Term Definition
Return Value
An integer number from 1 to 7.
Remarks
In contrast to Microsoft Excel, which stores dates as serial numbers, DAX works with
dates and times in a datetime format. If you need to display dates as serial numbers,
you can use the formatting options in Excel.
You can also type dates in an accepted text representation of a date, but to avoid
unexpected results, it is best to convert the text date to a datetime format first.
When the date argument is a text representation of the date, the function uses the locale
and date/time settings of the client computer to understand the text value in order to
perform the conversion. If the current date/time settings represent dates in the format of
Month/Day/Year, then the string, "1/8/2009", is interpreted as a datetime value
equivalent to January 8th of 2009. However, if the current date/time settings represent
100
dates in the format of Day/Month/Year, then the same string would be interpreted as a
datetime value equivalent to August 1st of 2009.
Example
Description
The following example gets the date from the [HireDate] column, adds 1, and displays
the weekday corresponding to that date. Because the return_type argument has been
omitted, the default format is used, in which 1 is Sunday and 7 is Saturday. If the result is
4, the day would be Wednesday.
Code
=WEEKDAY([HireDate]+1)
See Also
Date and Time functions
WEEKNUM
YEARFRAC
WEEKNUM Function
Returns the week number for the given date and year according to the return_type
value. The week number indicates where the week falls numerically within a year.
Syntax
WEEKNUM(<date>, <return_type>)
Parameters
Term Definition
101
Term Definition
2 Week begins on
Monday. Weekdays
are numbered 1
through 7.
Return Value
An integer number.
Remarks
In contrast to Microsoft Excel, which stores dates as serial numbers, DAX uses a datetime
data type to work with dates and times. If the source data is in a different format, DAX
implicitly converts the data to datetime to perform calculations.
By default, the WEEKNUM function uses a calendar convention in which the week
containing January 1 is considered to be the first week of the year. However, the ISO
8601 calendar standard, widely used in Europe, defines the first week as the one with the
majority of days (four or more) falling in the new year. This means that for years in which
there are three days or less in the first week of January, the WEEKNUM function returns
week numbers that are different from the ISO 8601 definition.
Example
Description
The following example returns the week number of the date February 14, 2010.
Code
=WEEKNUM("Feb 14, 2010", 2)
Example
Description
The following example returns the week number of the date stored in the column,
HireDate, from the table, Employees.
Code
=WEEKNUM('Employees'[HireDate])
See Also
Date and Time functions
YEARFRAC
WEEKDAY
102
YEAR Function
Returns the year of a date as a four digit integer in the range 1900-9999.
Syntax
YEAR(<date>)
Parameters
Term Definition
Return Value
An integer in the range 1900-9999.
Remarks
In contrast to Microsoft Excel, which stores dates as serial numbers, DAX uses a datetime
data type to work with dates and times.
Dates should be entered by using the DATE function, or as results of other formulas or
functions. You can also enter dates in accepted text representations of a date, such as
March 3, 2007, or Mar-3-2003.
Values returned by the YEAR, MONTH, and DAY functions will be Gregorian values
regardless of the display format for the supplied date value. For example, if the display
format of the supplied date uses the Hijri calendar, the returned values for the YEAR,
MONTH, and DAY functions will be values associated with the equivalent Gregorian date.
When the date argument is a text representation of the date, the function uses the locale
and date time settings of the client computer to understand the text value in order to
perform the conversion. Errors may arise if the format of strings is incompatible with the
current locale settings. For example, if your locale defines dates to be formatted as
month/day/year, and the date is provided as day/month/year, then 25/1/2009 will not be
interpreted as January 25th of 2009 but as an invalid date.
Example
Description
The following example returns 2007.
Code
=YEAR("March 2007")
Example: Date as Result of Expression
Description
103
The following example returns the year for today's date.
Code
=YEAR(TODAY())
See Also
Date and Time functions
HOUR
MINUTE
YEAR
SECOND
YEARFRAC Function
Calculates the fraction of the year represented by the number of whole days between
two dates. Use the YEARFRAC worksheet function to identify the proportion of a whole
year's benefits or obligations to assign to a specific term.
Syntax
Term Definition
Basis Description
0 US (NASD) 30/360
1 Actual/actual
2 Actual/360
3 Actual/365
4 European 30/360
104
Term Definition
Return Value
A decimal number. The internal data type is a signed IEEE 64-bit (8-byte) double-
precision floating-point number.
Remarks
In contrast to Microsoft Excel, which stores dates as serial numbers, DAX uses a datetime
format to work with dates and times. If you need to view dates as serial numbers, you
can use the formatting options in Excel.
If start_date or end_date are not valid dates, YEARFRAC returns an error.
If basis < 0 or if basis > 4, YEARFRAC returns an error.
Example
Description
The following example returns the fraction of a year represented by the difference
between the dates in the two columns, TransactionDate and ShippingDate:
Code
=YEARFRAC(Orders[TransactionDate],Orders[ShippingDate])
Example
Description
The following example returns the fraction of a year represented by the difference
between the dates, January 1 and March 1:
Code
=YEARFRAC("Jan 1 2007","Mar 1 2007")
Comments
Use four-digit years whenever possible, to avoid getting unexpected results. When the
year is truncated, the current year is assumed. When the date is or omitted, the first date
of the month is assumed.
The second argument, basis, has also been omitted. Therefore, the year fraction is
calculated according to the US (NASD) 30/360 standard.
See Also
Date and Time functions
WEEKNUM
YEARFRAC
WEEKDAY
105
Filter Functions
The filter and value functions in DAX are some of the most complex and powerful, and
differ greatly 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. For a discussion of context, see Context in DAX Formulas.
In this Section
ALL Function
ALLEXCEPT Function
ALLNOBLANKROW Function
ALLSELECTED Function
CALCULATE Function
CALCULATETABLE Function
DISTINCT Function
EARLIER Function
EARLIEST Function
FILTER Function
FILTERS Function
HASONEFILTER Function
HASONEVALUE Function
ISCROSSFILTERED Function
ISFILTERED Function
RELATED Function
RELATEDTABLE Function
VALUES Function
Reference
Using DAX
Basic DAX Syntax
Related Sections
Date and Time Functions (DAX)
Aggregation Functions (DAX)
Logical Functions (DAX)
Filter and Value Functions (DAX)
Math and Trigonometric Functions (DAX)
See Also
106
Getting Started with Data Analysis Expressions (DAX)
ALL Function
Returns all the rows in a table, or all the values in a column, ignoring any filters that
might have been applied. This function is useful for clearing filters and creating
calculations on all the rows in a table.
Syntax
Term Definition
The argument to the ALL function must be either a reference to a base table or a
reference to a base column. You cannot use table expressions or column expressions
with the ALL function.
Return Value
The table or column with filters removed.
Remarks
This function is not used by itself, but serves as an intermediate function that can be
used to change the set of results over which some other calculation is performed.
As described in the following table, you can use the ALL and ALLEXCEPT functions in
different scenarios.
107
Function and Usage Description
ratio of an aggregated value to the total
value. The first example demonstrates this
scenario.
ALL (Column[, Column[, …]]) Removes all filters from the specified
columns in the table; all other filters on
other columns in the table still apply. All
column arguments must come from the
same table.
The ALL(Column) variant is useful when you
want to remove the context filters for one
or more specific columns and to keep all
other context filters.
The second and third examples
demonstrate this scenario.
ALLEXCEPT(Table, Column1 [,Column2]...) Removes all context filters in the table
except filters that are applied to the
specified columns.
This is a convenient shortcut for situations
in which you want to remove the filters on
many, but not all, columns in a table.
108
All Reseller Column Labels
Sales
Code
=SUMX(ResellerSales_USD,
ResellerSales_USD[SalesAmount_USD])/SUMX(ALL(ResellerSales_USD),
ResellerSales_USD[SalesAmount_USD])
Comments
The formula is constructed as follows:
1. The numerator, SUMX(ResellerSales_USD,
ResellerSales_USD[SalesAmount_USD]), is the sum of the values in
ResellerSales_USD[SalesAmount_USD] for the current cell in the PivotTable, with
context filters applied on CalendarYear and ProductCategoryName.
2. For the denominator, you start by specifying a table, ResellerSales_USD, and use the
ALL function to remove all context filters on the table.
3. You then use the SUMX function to sum the values in the
ResellerSales_USD[SalesAmount_USD] column. In other words, you get the sum of
ResellerSales_USD[SalesAmount_USD] for all resellers sales.
For more information about creating measures, see Create a Measure.
Note
The above example uses the tables, ResellerSales_USD, DateTime, and
ProductCategory from the DAX sample workbook. For more information about
samples, see Get Sample Data .
Example: Calculate Ratio of Product Sales to Total Sales Through Current
Year
Description
Assume that you want to create a table showing the percentage of sales compared over
the years for each product category (ProductCategoryName). To obtain the percentage
for each year over each value of ProductCategoryName, you need to divide the sum of
109
sales for that particular year and product category by the sum of sales for the same
product category over all years. In other words, you want to keep the filter on
ProductCategoryName but remove the filter on the year when calculating the
denominator of the percentage.
The following table shows the results when a new measure, Reseller Sales Year, is
created using the formula shown in the code section. To see how this works, add the
field, CalendarYear, to the Row Labels area of the PivotTable, and add the field,
ProductCategoryName, to the Column Labels area. To view the results as percentages,
use Excel's formatting features to apply a percentage number format to the cells
containing the measure, Reseller Sales Year.
Code
=SUMX(ResellerSales_USD, ResellerSales_USD[SalesAmount_USD])/CALCULATE(
SUM( ResellerSales_USD[SalesAmount_USD]), ALL(DateTime[CalendarYear]))
Comments
The formula is constructed as follows:
1. The numerator, SUMX(ResellerSales_USD,
ResellerSales_USD[SalesAmount_USD]), is the sum of the values in
ResellerSales_USD[SalesAmount_USD] for the current cell in the pivot table, with
context filters applied on the columns CalendarYear and ProductCategoryName.
2. For the denominator, you remove the existing filter on CalendarYear by using the
ALL(Column) function. This calculates the sum over the remaining rows on the
ResellerSales_USD table, after applying the existing context filters from the column
labels. The net effect is that for the denominator the sum is calculated over the
selected ProductCategoryName (the implied context filter) and for all values in Year.
For more information about creating measures, see Create a Measure.
110
Note
This example uses the tables, ResellerSales_USD, DateTime, and ProductCategory
from the DAX sample workbook. For more information about samples, see Get
Sample Data .
Example: Calculate Contribution of Product Categories to Total Sales Per
Year
Description
Assume that you want to create a table that shows the percentage of sales for each
product category, on a year-by-year basis. To obtain the percentage for each product
category in a particular year, you need to calculate the sum of sales for that particular
product category (ProductCategoryName) in year , and then divide the resulting value by
the sum of sales for the year over all product categories. In other words, you want to
keep the filter on year but remove the filter on ProductCategoryName when calculating
the denominator of the percentage.
The following table shows the results when a new measure, Reseller Sales
CategoryName, is created using the formula shown in the code section. To see how this
works, add the field, CalendarYear to the Row Labels area of the PivotTable, and add the
field, ProductCategoryName, to the Column Labels area. Then add the new measure to
the Values area of the PivotTable. To view the results as percentages, use Excel's
formatting features to apply a percentage number format to the cells that contain the
new measure, Reseller Sales CategoryName.
Code
=SUMX(ResellerSales_USD, ResellerSales_USD[SalesAmount_USD])/CALCULATE(
SUM( ResellerSales_USD[SalesAmount_USD]),
ALL(ProductCategory[ProductCategoryName]))
Comments
111
The formula is constructed as follows:
1. The numerator, SUMX(ResellerSales_USD,
ResellerSales_USD[SalesAmount_USD]), is the sum of the values in
ResellerSales_USD[SalesAmount_USD] for the current cell in the PivotTable, with
context filters applied on the fields, CalendarYear and ProductCategoryName.
2. For the denominator, you use the function, ALL(Column), to remove the filter on
ProductCategoryName and calculate the sum over the remaining rows on the
ResellerSales_USD table, after applying the existing context filters from the row
labels. The net effect is that, for the denominator, the sum is calculated over the
selected Year (the implied context filter) and for all values of ProductCategoryName.
For more information about creating measures, see Create a Measure.
Note
This example uses the tables, ResellerSales_USD, DateTime, and ProductCategory
from the DAX sample workbook. For more information about samples, see Get
Sample Data.
See Also
Filter and value functions
ALL
ALLEXCEPT
FILTER
ALLEXCEPT Function
Removes all context filters in the table except filters that have been applied to the
specified columns.
Syntax
ALLEXCEPT(<table>,<column>[,<column>[,…]])
Parameters
Term Definition
112
The first argument to the ALLEXCEPT function must be a reference to a base table; all
subsequent arguments must be references to base columns. You cannot use table
expressions or column expressions with the ALLEXCEPT function.
Return Value
A table with all filters removed except for the filters on the specified columns.
Remarks
This function is not used by itself, but serves as an intermediate function that can be
used to change the set of results over which some other calculation is performed.
As described in the following table, you can use the ALL and ALLEXCEPT functions in
different scenarios.
113
Example
Description
The following example presents a formula that you can use in a measure. For more
information about how to create a measure, see Create a Measure.
The formula sums SalesAmount_USD and uses the ALLEXCEPT function to remove any
context filters on the DateTime table except if the filter has been applied to the
CalendarYear column.
Note
The above example uses the tables, ResellerSales_USD and DateTime from the
DAX sample workbook. For more information about samples, see Get Sample
Data .
Code
=CALCULATE(SUM(ResellerSales_USD[SalesAmount_USD]), ALLEXCEPT(DateTime,
DateTime[CalendarYear]))
Comments
Because the formula uses ALLEXCEPT, whenever any column but CalendarYear from the
table DateTime is used to slice the PivotTable, the formula will remove any slicer filters,
providing a value equal to the sum of SalesAmount_USD for the column label value, as
shown in Table 1.
However, if the column CalendarYear is used to slice the PivotTable, the results are
different. Because CalendarYear is specified as the argument to ALLEXCEPT, when the
data is sliced on the year, a filter will be applied on years at the row level, as shown in
Table 2. The user is encouraged to compare these tables to understand the behavior of
ALLEXCEPT().
See Also
Filter and value functions
ALL
FILTER
ALLNOBLANKROW Function
From the parent table of a relationship, returns all rows but the blank row, or all distinct
values of a column but the blank row, and disregards any context filters that might exist.
Syntax
ALLNOBLANKROW(<table>|<column>)
Parameters
114
Term Definition
Only one parameter must be passed; the parameter is either a table or a column.
Return Value
A table, when the passed parameter was a table, or a column of values, when the passed
parameter was a column.
Remarks
The ALLNOBLANKROW function only filters the blank row that a parent table, in a
relationship, will show when there are one or more rows in the child table that have non-
matching values to the parent column. See the example below for a thorough
explanation.
The following table summarizes the variations of ALL that are provided in DAX, and their
differences:
For a general description of how the ALL function works, together with step-by-step
examples that use ALL(Table) and ALL(Column), see ALL Function (DAX).
Example
Description
115
In the sample data, the ResellerSales_USD table contains one row that has no values and
therefore cannot be related to any of the parent tables in the relationships within the
workbook. You will use this table in a PivotTable so that you can see the blank row
behavior and how to handle counts on unrelated data.
Step 1: Verify the unrelated data
Open the PowerPivot window, then select the ResellerSales_USD table. In the
ProductKey column, filter for blank values. One row will remain. In that row, all column
values should be blank except for SalesOrderLineNumber.
Step 2: Create a PivotTable
Create a new PivotTable, then drag the column, datetime.[Calendar Year], to the Row
Labels pane. The following table shows the expected results:
Row Labels
2005
2006
2007
2008
Grand Total
Note the blank label between 2008 and Grand Total. This blank label represents the
Unknown member, which is a special group that is created to account for any values in
the child table that have no matching value in the parent table, in this example the
datetime.[Calendar Year] column.
When you see this blank label in the PivotTable, you know that in some of the tables that
are related to the column, datetime.[Calendar Year], there are either blank values or non-
matching values. The parent table is the one that shows the blank label, but the rows
that do not match are in one or more of the child tables.
The rows that get added to this blank label group are either values that do not match
any value in the parent table-- for example, a date that does not exist in the datetime
table-- or null values, meaning no value for date at all. In this example we have placed a
blank value in all columns of the child sales table. Having more values in the parent table
than in the children tables does not cause a problem.
Step 3: Count rows using ALL and ALLNONBLANK
Add the following two measures to the datetime table, to count the table rows:
Countrows ALLNOBLANK of datetime, Countrows ALL of datetime. The formulas
that you can use to define these measures are given in the code section following.
116
On a blank PivotTable add datetime.[Calendar Year] column to the row labels, and then
add the newly created measures. The results should look like the following table:
The results show a difference of 1 row in the table rows count. However, if you open the
PowerPivot window and select the datetime table, you cannot find any blank row in the
table because the special blank row mentioned here is the Unknown member.
Step 4: Verify that the count is accurate
In order to prove that the ALLNOBLANKROW does not count any truly blank rows, and
only handles the special blank row on the parent table only, add the following two
measures to the ResellerSales_USD table: Countrows ALLNOBLANKROW of
ResellerSales_USD, Countrows ALL of ResellerSales_USD.
Create a new PivotTable, and drag the column, datetime.[Calendar Year], to the Row
Labels pane. Now add the measures that you just created. The results should look like
the following:
117
Now the two measures have the same results. That is because the ALLNOBLANKROW
function does not count truly blank rows in a table, but only handles the blank row that
is a special case generated in a parent table, when one or more of the child tables in the
relationship contain non-matching values or blank values.
Code
// Countrows ALLNOBLANK of datetime
= COUNTROWS(ALLNOBLANKROW('DateTime'))
Comments
See Also
Filter and value functions
ALL
FILTER
ALLSELECTED Function
Removes context filters from columns and rows in the current query, while retaining all
other context filters or explicit filters.
The ALLSELECTED function gets the context that represents all rows and columns in the
query, while keeping explicit filters and contexts other than row and column filters. This
function can be used to obtain visual totals in queries.
Syntax
ALLSELECTED([<tableName> | <columnName>])
Parameters
Parameter Description
118
using standard DAX syntax. This
parameter cannot be an
expression. This parameter is
optional.
Return Value
The context of the query without any column and row filters.
Exceptions
Remarks
• This function takes one or no arguments. If there is one argument, the argument is
either tableName or columnName.
• This function is different from ALL() because it retains all filters explicitly set within
the query, and it retains all context filters other than row and column filters.
Example
Description
The following example shows how to generate different levels of visual totals in a table
report using DAX expressions. In the report two (2) previous filters have been applied to
the Reseller Sales data; one on Sales Territory Group = Europe and the other on
Promotion Type = Volume Discount. Once filters have been applied, visual totals can be
calculated for the entire report, for All Years, or for All Product Categories. Also, for
illustration purposes the grand total for All Reseller Sales is obtained too, removing all
filters in the report. Evaluating the following DAX expression results in a table with all the
information needed to build a table with Visual Totals.
Code
define
measure 'Reseller Sales'[Reseller Sales Amount]=sum('Reseller
Sales'[Sales Amount])
measure 'Reseller Sales'[Reseller Grand Total]=calculate(sum('Reseller
Sales'[Sales Amount]), ALL('Reseller Sales'))
measure 'Reseller Sales'[Reseller Visual Total]=calculate(sum('Reseller
Sales'[Sales Amount]), ALLSELECTED())
119
measure 'Reseller Sales'[Reseller Visual Total for All of Calendar
Year]=calculate(sum('Reseller Sales'[Sales Amount]),
ALLSELECTED('Date'[Calendar Year]))
measure 'Reseller Sales'[Reseller Visual Total for All of Product
Category Name]=calculate(sum('Reseller Sales'[Sales Amount]),
ALLSELECTED('Product Category'[Product Category Name]))
evaluate
CalculateTable(
//CT table expression
summarize(
//summarize table expression
crossjoin(distinct('Product Category'[Product Category Name]),
distinct('Date'[Calendar Year]))
//First Group by expression
, 'Product Category'[Product Category Name]
//Second Group by expression
, 'Date'[Calendar Year]
//Summary expressions
, "Reseller Sales Amount", [Reseller Sales Amount]
, "Reseller Grand Total", [Reseller Grand Total]
, "Reseller Visual Total", [Reseller Visual Total]
, "Reseller Visual Total for All of Calendar Year", [Reseller Visual
Total for All of Calendar Year]
, "Reseller Visual Total for All of Product Category Name", [Reseller
Visual Total for All of Product Category Name]
)
//CT filters
, 'Sales Territory'[Sales Territory Group]="Europe",
'Promotion'[Promotion Type]="Volume Discount"
)
order by [Product Category Name], [Calendar Year]
120
Comments
After executing the above expression in SQL Server Management Studio against
AdventureWorks DW Tabular Model 2012 you obtain the following results:
121
[Product [Reseller [Reseller Grand [Reseller [Reseller [Reseller
Category [Calend Sales Total] Visual Total] Visual Total Visual Total
Name] ar Year] Amount] for All of for All of
Calendar Product
Year] Category
Name]
23 87 39
Bikes 2006 80450596.98 877006.79 689287.79
23 87 39
Clothing 2000 80450596.98 877006.79 95090.775
23 87 7
Clothing 2001 80450596.98 877006.79 95090.775
23 87 7
Clothing 2002 12132.433 80450596.98 877006.79 95090.775 91495.310
4 23 87 7 4
Clothing 2003 58234.221 80450596.98 877006.79 95090.775 572927.01
4 23 87 7 36
Clothing 2004 24724.120 80450596.98 877006.79 95090.775 212584.47
9 23 87 7 47
Clothing 2005 80450596.98 877006.79 95090.775
23 87 7
Clothing 2006 80450596.98 877006.79 95090.775
23 87 7
Componen 2000 80450596.98 877006.79 53842.211
ts 23 87 1
Componen 2001 80450596.98 877006.79 53842.211
ts 23 87 1
Componen 2002 4958.1457 80450596.98 877006.79 53842.211 91495.310
ts 23 87 1 4
Componen 2003 48884.065 80450596.98 877006.79 53842.211 572927.01
ts 4 23 87 1 36
Componen 2004 80450596.98 877006.79 53842.211 212584.47
ts 23 87 1 47
Componen 2005 80450596.98 877006.79 53842.211
ts 23 87 1
122
[Product [Reseller [Reseller Grand [Reseller [Reseller [Reseller
Category [Calend Sales Total] Visual Total] Visual Total Visual Total
Name] ar Year] Amount] for All of for All of
Calendar Product
Year] Category
Name]
Example
Description
The following example shows the usage of ALLSELECTED() with no arguments to show
how to calculate a ratio over the total value shown in a table that has been filtered by
using horizontal and vertical slicers. This example uses SQL Server 2012, PowerPivot for
Excel and PowerPivot Sample Data (DAX_AdventureWorks).
• In the PowerPivot field list, drag the column, ResellerSales[SalesAmount_USD], to the
Values area.
• Drag Promotion[PromotionType] to the Slicers Vertical area. Select the slicers for
Discontinued Product, Excess Inventory and Seasonal Discount.
123
• Drag SalesTerritory[SalesTerritoryGroup] to the Slicers Horizontal area. Select the
slicer for Europe.
• The value of Sum Of SalesAmount_USD should be $19,614.37
• Drag ProductCategory[ProductCategoryName] to the Row Labels area and
DateTime[CalendarYear] to the Column Labels area.
Your table should look similar to:
SalesTerritory
Group
Europe North
America
Pacific NA
Promotion
Type
Discontinue Sum of Colum
d Product SalesAmount n
_USD Labels
Excess Row Labels 2006 2007 2008 Grand
Inventory Total
New Accessories $1,111. $3,414. $4,525.
Product 22 43 66
No Bikes $8,834. $6,253. $15,088
Discount 94 78 .72
Seasonal Grand Total $9,946 $3,414 $6,253 $19,614
Discount .16 .43 .78 .37
Volume
Discount
• Using a hand calculator, verify that the amount $3,414.43 (for Accessories in 2007)
represents 17.41% of $19,614.37.
• Using a hand calculator, verify that the amount $6,253.78 (for Bikes in 2008)
represents 31.88% of $19,614.37.
• Using a hand calculator, verify that the amount $15,088.72 (for Bikes Grand Total)
represents 76.93% of $19,614.37.
124
• Remove ResellerSales[SalesAmount_USD] from the Values area.
• Create a measure, named Reseller Sales Ratio, in the ResellerSales table, using the
following formula (format the result as percentage):
Code
=SUM(ResellerSales_USD[SalesAmount_USD])/
CALCULATE(SUM(ResellerSales_USD[SalesAmount_USD]), ALLSELECTED())
Comments
Your table should look like this:
SalesTerritoryGroup
Europe North
America
Pacific NA
PromotionType
Discontinued Reseller Column
Product Sales Ratio Labels
Excess Inventory Row 2006 2007 2008 Grand
Labels Total
New Product Accessories 5.67 % 17.41 23.07
% %
No Discount Bikes 45.04 % 31.88 76.93
% %
Seasonal Grand 50.71 % 17.41 31.88 100.00
Discount Total % % %
Volume
Discount
• Compare your handheld calculator results with those given by Reseller Sales Ratio
and they should match; your denominator value is fixed as the value at the bottom of
the table.
• Because the CALCULATE formula in the denominator uses the ALLSELECTED function,
the denominator represents the grand total of sales, at the bottom of the table, after
the vertical, horizontal and page slicers have been applied; but, before the row and
column slicers are applied .
125
Note: if you have explicit filters in your expression, those filters are also applied to
the expression.
CALCULATE Function
Evaluates an expression in a context that is modified by the specified filters.
Syntax
CALCULATE(<expression>,<filter1>,<filter2>…)
Parameters
Term Definition
The expression used as the first parameter is essentially the same as a measure.
The following restrictions apply to Boolean expressions that are used as arguments:
• The expression cannot reference a measure.
• The expression cannot use a nested CALCULATE function.
• The expression cannot use any function that scans a table or returns a table,
including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that
calculate a scalar value.
Return Value
The value that is the result of the expression.
Remarks
If the 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. For
each column used in a filter argument, any existing filters on that column are removed,
and the filter used in the filter argument is applied instead.
Example
Description
To calculate the ratio of current reseller sales to all reseller sales, you add to the
PivotTable a measure that calculates the sum of sales for the current cell (the numerator),
and then divides that sum by the total sales for all resellers (the denominator). To ensure
126
that the denominator remains the same regardless of how the PivotTable might be
filtering or grouping the data, the part of the formula that represents the denominator
must use the ALL function to clear any filters and create the correct total.
The following table shows the results when the new measure, named All Reseller Sales
Ratio, is created by using the formula in the code section.
To see how this works, add the field, CalendarYear, to the Row Labels area of the
PivotTable, and add the field, ProductCategoryName, to the Column Labels area. Then
add the new measure to the Values area of the PivotTable. To display the numbers as
percentages, apply percentage number formatting to the area of the PivotTable that
contains the new measure, All Reseller Sales Ratio.
Code
=( SUM('ResellerSales_USD'[SalesAmount_USD]))
/CALCULATE( SUM('ResellerSales_USD'[SalesAmount_USD])
,ALL('ResellerSales_USD'))
Comments
The CALCULATE expression in the denominator enables the sum expression to include all
rows in the calculation. This overrides the implicit filters for CalendarYear and
ProductCategoryName that exist for the numerator part of the expression.
Related Functions
Whereas the CALCULATE function requires as its first argument an expression that
returns a single value, the CALCULATETABLE function takes a table of values.
See Also
CALCULATETABLE Function
Filter and value functions
127
CALCULATETABLE Function
Evaluates a table expression in a context modified by the given filters.
Syntax
CALCULATETABLE(<expression>,<filter1>,<filter2>,…)
Parameters
Term Definition
The expression used as the first parameter must be a function that returns a table.
The following restrictions apply to Boolean expressions that are used as arguments:
• The expression cannot reference a measure.
• The expression cannot use a nested CALCULATE function.
• The expression cannot use any function that scans a table or returns a table,
including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that
calculates a scalar value.
Return Value
A table of values.
Remarks
The CALCULATETABLE function changes the context in which the data is filtered, and
evaluates the expression in the new context that you specify. For each column used in a
filter argument, any existing filters on that column are removed, and the filter used in the
filter argument is applied instead.
This function is a synonym for the RELATEDTABLE function.
Example
Description
The following example uses the CALCULATETABLE function to get the sum of Internet
sales for 2006. This value is later used to calculate the ratio of Internet sales compared to
all sales for the year 2006.
The following table shows the results from the following formula.
128
Row Labels Internet SalesAmount_USD CalculateTable 2006 Internet Sales to
Internet Sales 2006 ratio
Code
=SUMX( CALCULATETABLE('InternetSales_USD',
'DateTime'[CalendarYear]=2006)
, [SalesAmount_USD])
See Also
RELATEDTABLE Function (DAX)
Filter and value functions
DISTINCT Function
Returns a one-column table that contains the distinct values from the specified column.
In other words, duplicate values are removed and only unique values are returned.
Note
This function cannot be used to return values into a cell or column on a
worksheet; rather, you nest the DISTINCT function within a formula, to get a list
of distinct values that can be passed to another function and then counted,
summed, or used for other operations.
Syntax
DISTINCT(<column>)
Parameters
Term Definition
129
Return Value
A column of unique values.
Remarks
The results of DISTINCT are affected by the current filter context. For example, if you use
the formula in the following example to create a measure, the results would change
whenever the table was filtered to show only a particular region or a time period.
Related Functions
The VALUES function is similar to DISTINCT; it can also be used to return a list of unique
values, and generally will return exactly the same results as DISTINCT. However, in some
context VALUES will return one additional special value. For more information,
see VALUES Function (DAX).
Example
Description
The following formula counts the number of unique customers who have generated
orders over the internet channel. The table that follows illustrates the possible results
when the formula is added to a PivotTable.
Code
=COUNTROWS(DISTINCT(InternetSales_USD[CustomerKey]))
Comments
Note that you cannot paste the list of values that DISTINCT returns directly into a
column. Instead, you pass the results of the DISTINCT function to another function that
counts, filters, or aggregates values by using the list. To make the example as simple as
possible, here the table of distinct values has been passed to the COUNTROWS function.
Also, note that the results are not additive. That is to say, the total number of unique
customers in 2007 is not the sum of unique customers of Accessories, Bikes and Clothing
for that year. The reason is that a customer can be counted in multiple groups.
130
See Also
Filter and value functions
FILTER
RELATED
VALUES
EARLIER Function
Returns the current value of the specified column in an outer evaluation pass of the
mentioned column.
EARLIER is useful for nested calculations where you want to use a certain value as an
input and produce calculations based on that input. In Microsoft Excel, you can do such
calculations only within the context of the current row; however, in DAX you can store
the value of the input and then make calculation using data from the entire table.
EARLIER is mostly used in the context of calculated columns.
Syntax
EARLIER(<column>, <number>)
Parameters
Term Definition
131
The performance of EARLIER might be slow because it theoretically, it might have to
perform a number of operations that is close to the total number of rows (in the column)
times the same number (depending on the syntax of the expression). For example if you
have 10 rows in the column, approximately a 100 operations could be required; if you
have 100 rows then close to 10,000 operations might be performed.
Note
In practice, the xVelocity in-memory analytics engine (VertiPaq) performs
optimizations to reduce the actual number of calculations, but you should be
cautious when creating formulas that involve recursion.
Example
Description
To illustrate the use of EARLIER, it is necessary to build a scenario that calculates a rank
value and then uses that rank value in other calculations.
The following example is based on this simple table, ProductSubcategory, which shows
the total sales for each ProductSubcategory.
The final table, including the ranking column is shown here.
18 Bib-Shorts $156,167.88 18
26 Bike Racks $220,720.70 14
27 Bike Stands $35,628.69 30
28 Bottles and Cages $59,342.43 24
5 Bottom Brackets $48,643.47 27
6 Brakes $62,113.16 23
19 Caps $47,934.54 28
7 Chains $8,847.08 35
29 Cleaners $16,882.62 32
8 Cranksets $191,522.09 15
9 Derailleurs $64,965.33 22
30 Fenders $41,974.10 29
10 Forks $74,727.66 21
20 Gloves $228,353.58 12
132
ProductSubcategoryK EnglishProductSubcategoryNa TotalSubcategorySal SubcategoryRankin
ey me es g
4 Handlebars $163,257.06 17
11 Headsets $57,659.99 25
31 Helmets $451,192.31 9
32 Hydration Packs $96,893.78 20
21 Jerseys $699,429.78 7
33 Lights 36
34 Locks $15,059.47 33
1 Mountain Bikes $34,305,864.29 2
12 Mountain Frames $4,511,170.68 4
35 Panniers 36
13 Pedals $140,422.20 19
36 Pumps $12,695.18 34
2 Road Bikes $40,551,696.34 1
14 Road Frames $3,636,398.71 5
15 Saddles $52,526.47 26
22 Shorts $385,707.80 10
23 Socks $28,337.85 31
24 Tights $189,179.37 16
37 Tires and Tubes $224,832.81 13
3 Touring Bikes $13,334,864.18 3
16 Touring Frames $1,545,344.02 6
25 Vests $240,990.04 11
17 Wheels $648,240.04 8
133
whereas equal values will have the same rank value and next value (after the equal
values) will have a non consecutive rank value. See the sample below.
A new calculated column, SubCategorySalesRanking, is created by using the following
formula.
Code
= COUNTROWS(FILTER(ProductSubcategory,
EARLIER(ProductSubcategory[TotalSubcategorySales])<ProductSubcategory[T
otalSubcategorySales]))+1
Comments
The following steps describe the method of calculation in more detail.
1. The EARLIER function gets the value of TotalSubcategorySales for the current row in
the table. In this case, because the process is starting, it is the first row in the table
2. EARLIER([TotalSubcategorySales]) evaluates to $156,167.88, the current row in the
outer loop.
3. The FILTER function now returns a table where all rows have a value of
TotalSubcategorySales larger than $156,167.88 (which is the current value for
EARLIER).
4. The COUNTROWS function counts the rows of the filtered table and assigns that
value to the new calculated column in the current row plus 1. Adding 1 is needed to
prevent the top ranked value from become a Blank.
5. The calculated column formula moves to the next row and repeats steps 1 to 4. These
steps are repeated until the end of the table is reached.
The EARLIER function will always get the value of the column prior to the current table
operation. If you need to get a value from the loop before that, set the second argument
to 2.
See Also
EARLIESTfunction
Filter and value functions
EARLIEST Function
Returns the current value of the specified column in an outer evaluation pass of the
specified column.
Syntax
EARLIEST(<column>)
Parameters
134
Term Definition
FILTER Function
Returns a table that represents a subset of another table or expression.
Syntax
FILTER(<table>,<filter>)
Parameters
Term Definition
Return Value
A table containing only the filtered rows.
135
Remarks
You can use FILTER to reduce the number of rows in the table that you are working with,
and use only specific data in calculations. FILTER is not used independently, but as a
function that is embedded in other functions that require a table as an argument.
Example
Description
The following example creates a report of Internet sales outside the United States by
using a measure that filters out sales in the United States, and then slicing by calendar
year and product categories. To create this measure, you filter the table, Internet Sales
USD, by using Sales Territory, and then use the filtered table in a SUMX function.
In this example, the expression FILTER('InternetSales_USD',
RELATED('SalesTerritory'[SalesTerritoryCountry])<>"United States")
returns a table that is a subset of Internet Sales minus all rows that belong to the United
States sales territory. The RELATED function is what links the Territory key in the Internet
Sales table to SalesTerritoryCountry in the SalesTerritory table.
The following table demonstrates the proof of concept for the measure, NON USA
Internet Sales, the formula for which is provided in the code section below. The table
compares all Internet sales with non- USA Internet sales, to show that the filter
expression works, by excluding United States sales from the computation.
To re-create this table, add the field, SalesTerritoryCountry, to the Row Labels area of
the PivotTable.
Table 1. Comparing total sales for U.S. vs. all other regions
The final report table shows the results when you create a PivotTable by using the
measure, NON USA Internet Sales. Add the field, CalendarYear, to the Row Labels area
of the PivotTable and add the field, ProductCategoryName, to the Column Labels area.
Table 2. Comparing non- U.S. sales by product categories
136
Non USA Column Labels
Internet Sales
Code
SUMX(FILTER('InternetSales_USD',
RELATED('SalesTerritory'[SalesTerritoryCountry])<>"United States")
,'InternetSales_USD'[SalesAmount_USD])
See Also
Filter and value functions
ALL
ALLEXCEPT
FILTERS Function
Returns the values that are directly applied as filters to columnName.
Syntax
FILTERS(<columnName>)
Parameters
Parameter Description
Return Value
The values that are directly applied as filters to columnName.
Remarks
137
Example
Description
The following example shows how to determine the number of direct filters a column
has.
Code
=COUNTROWS(FILTERS(ResellerSales_USD[ProductKey]))
Comments
The example above lets you know how many direct filters on
ResellerSales_USD[ProductKey] have been applied to the context where the expression is
being evaluated.
HASONEFILTER Function
Returns TRUE when the number of directly filtered values on columnName is one;
otherwise returns FALSE.
Syntax
HASONEFILTER(<columnName>)
Parameters
Parameter Description
Return Value
TRUE when the number of directly filtered values on columnName is one; otherwise
returns FALSE.
Remarks
1. An equivalent expression for HASONEFILTER() is
COUNTROWS(FILTERS(<columnName>)) = 1.
2. This function is similar to HASONEVALUE() with the difference that HASONEVALUE()
works based on cross-filters while HASONEFILTER() works by a direct filter.
Example
Description
The following example shows how to use HASONEFILTER() to return the filter for
ResellerSales_USD[ProductKey]) if there is one filter, or to return BLANK if there are no
filters or more than one filter on ResellerSales_USD[ProductKey]).
138
Code
=IF(HASONEFILTER(ResellerSales_USD[ProductKey]),FILTERS(ResellerSales_U
SD[ProductKey]),BLANK())
Comments
HASONEVALUE Function
Returns TRUE when the context for columnName has been filtered down to one distinct
value only. Otherwise is FALSE.
Syntax
HASONEVALUE(<columnName>)
Parameters
Parameter Description
Return Value
TRUE when the context for columnName has been filtered down to one distinct value
only. Otherwise is FALSE.
Remarks
• An equivalent expression for HASONEVALUE() is
COUNTROWS(VALUES(<columnName>)) = 1.
Example
Description
In the following example you want to create a formula that verifies if the context is being
sliced by one value in order to estimate a percentage against a predefined scenario; in
this case you want to compare Reseller Sales against sales in 2007, then you need to
know if the context is filtered by single years. Also, if the comparison is meaningless you
want to return BLANK.
If you want to follow the scenario, you can download the spreadsheet with the model
from PowerPivot Sample Data spreadsheet.
Create a measure named [ResellerSales compared to 2007] using the following
expression:
Code
139
=IF(HASONEVALUE(DateTime[CalendarYear]),SUM(ResellerSales_USD[SalesAmou
nt_USD])/CALCULATE(SUM(ResellerSales_USD[SalesAmount_USD]),DateTime[Cal
endarYear]=2007),BLANK())
Comments
1. After creating the measure you should have an empty result under [ResellerSales
compared to 2007], as shown below:
The BLANK cell in the result is because you don't have single year filters anywhere in
your context.
2. Drag DateTime[CalendarYear] to the Column Labels box; your table should look like
this:
Column
Labels
2005 2006 2007 2008
ResellerSales 24.83 % 74.88 % 100.00 % 50.73 %
compared to 2007
ResellerSales Column
compared to 2007 Labels
Row Labels 2005 2006 2007 2008
Accessories 6.74 % 31.40 % 100.00 % 55.58 %
Bikes 28.69 % 77.92 % 100.00 % 53.46 %
Clothing 3.90 % 55.86 % 100.00 % 44.92 %
Components 11.05 % 65.99 % 100.00 % 38.65 %
Grand Total 24.83 % 74.88 % 100.00 % 50.73 %
140
Did you notice that Grand Totals appeared at the bottom of the columns but not for
the rows? This is because the context for Grand Totals on rows implies more than
one year; but for columns implies a single year.
4. Drag DateTime[CalendarYear] to the Horizontal Slicers box, and drag
SalesTerritory[SalesTerritoryGroup] to the Horizontal Labels box. You should have
an empty results set, because your table contains data for multiple years. Select 2006
in the slicer and your table should now have data again. Try other years to see how
the results change.
5. In summary, HASONEVALUE() allows you to identify if your expression is being
evaluated in the context of a single value for columnName.
ISCROSSFILTERED Function
Returns TRUE when columnName or another column in the same or related table is
being filtered.
Syntax
ISCROSSFILTERED(<columnName>)
Parameters
Parameter Description
Return Value
TRUE when columnName or another column in the same or related table is being
filtered. Otherwise returns FALSE.
Remarks
• A column is said to be cross-filtered when a filter applied to another column in the
same table or in a related table affects columnName by filtering it. A column is said
to be filtered directly when the filter or filters apply over the column.
• The related function ISFILTERED Function (DAX) returns TRUE when columnName is
filtered directly.
Example
Description
The following example creates a measure and then presents different scenarios to
explain the behavior of ISCROSSFILTERED(). The scenarios can be followed by
downloading the DAX_AdventureWorks spreadsheet.
First, create the following measure [Is ProductName Cross Filtered] in the [Product] table.
141
Code
=ISCROSSFILTERED(Product[ProductName])
Comments
Understanding ISCROSSFILTERED():
1. After you create the measure, the PivotTable should show that [Is ProductName
Cross Filtered] is FALSE, because the expression is not being filtered at all. Now, you
should have something like this:
If nothing appears in the PivotTable, drag the column [Is ProductName Cross
Filtered] to the Values box.
2. Drag DateTime[CalendarYear] to the Column Labels box and drag
SalesTerritory[SalesTerritoryGroup] to the Row Labels box; all values should appear
as FALSE. Now, you should have something like this:
Is Product Column
Name Labels
CrossFiltered
Row Labels 2005 2006 2007 2008 Grand
Total
Europe FALSE FALSE FALSE FALSE FALSE FALSE
NA FALSE FALSE FALSE FALSE FALSE FALSE
North America FALSE FALSE FALSE FALSE FALSE FALSE
Pacific FALSE FALSE FALSE FALSE FALSE FALSE
FALSE FALSE FALSE FALSE FALSE FALSE
Grand Total FALSE FALSE FALSE FALSE FALSE FALSE
You are seeing the value FALSE in all cells because neither DateTime[CalendarYear] or
SalesTerritory[SalesTerritoryGroup] have any filtering effect over
Product[ProductName].
3. Drag the column ProductCategory[ProductCategoryName] to the Slicers Horizontal
box and ProductSubCategory[ProductSubCategoryName] to the Slicers Vertical box.
All values should still appear as FALSE, because when you add a column to the slicers
142
box you haven't yet selected a slicing set. Therefore, you should have something like
this:
ProductCategory
Name
Accessories Bikes
Clothing Compon
ents
143
Gloves
Handlebars
Headsets
4. Select any item in the slicers and your table will now turn all cells to TRUE because
you are now filtering the Product[ProductName] column through the related tables
ProductCategory and ProductSubcategory. Your results should look like this:
ProductCategory
Name
Accessories Bikes
Clothing Compone
nts
144
Cleaners
Cranksets
Derailleurs
Fenders
Forks
Gloves
Handlebars
Headsets
ISFILTERED Function
Returns TRUE when columnName is being filtered directly. If there is no filter on the
column or if the filtering happens because a different column in the same table or in a
related table is being filtered then the function returns FALSE.
Syntax
ISFILTERED(<columnName>)
Parameters
Parameter Description
145
cannot be an expression.
Return Value
TRUE when columnName is being filtered directly.
Remarks
• columnName is said to be filtered directly when the filter or filters apply over the
column; a column is said to be cross-filtered when a filter applied to another column
in the same table or in a related table affects columnName the column by filtering it
as well.
• The related function ISCROSSFILTERED Function (DAX) returns TRUE when
columnName or another column in the same or related table is being filtered.
Example
Description
The following example creates a measure and then presents different scenarios to
explain the behavior of ISFILTERED(). The scenarios can be followed by downloading
the Data Analysis Expressions (DAX) Sample Data spreadsheet.
First, create the following measure [Is ProductName Filtered directly] in the [Product]
table.
Code
=ISFILTERED(Product[ProductName])
Comments
Understanding ISFILTERED():
1. After you create the measure, the pivot table should show that [Is ProductName
Filtered directly] is FALSE, because the expression is not being filtered at all. Now,
you should have something like this:
If nothing appears in the pivot table, drag [Is ProductName Filtered directly] to the
Values box.
2. Drag ProductCategory[ProductCategoryName] to the Row Labels box; all values
should still be FALSE and your table should look something like this:
146
Bikes FALSE
Clothing FALSE
Components FALSE
FALSE
Grand Total FALSE
Is ProductName Column
Filtered directly Labels
Row Labels Current Grand Total
Accessories FALSE FALSE FALSE
Bikes FALSE FALSE FALSE
Clothing FALSE FALSE FALSE
Components FALSE FALSE FALSE
FALSE FALSE FALSE
Grand Total FALSE FALSE FALSE
The table still has many values of FALSE because Product[Status] doesn't filter
Product[Name] directly.
4. The last step in this process is to drag Product[Name] to the Report Filter box. At
this point nothing should have changed; however, once you select a product name,
the table values should change to TRUE. Depending on the product you selected
your table should look like this:
147
Filtered directly
Row Labels Current Grand Total
Accessories TRUE TRUE
Bikes TRUE TRUE
Clothing TRUE TRUE
Components TRUE TRUE
TRUE TRUE
Grand Total TRUE TRUE
KEEPFILTERS Function
Modifies how filters are applied while evaluating a CALCULATE or CALCULATETABLE
function.
Syntax
KEEPFILTERS(<expression>)
Parameters
Term Definition
Return Value
No return value.
Remarks
148
You use KEEPFILTERS within the context CALCULATE and CALCULATETABLE functions, to
override the standard behavior of those functions.
By default, filter arguments s in functions such as CALCULATE are used as the context for
evaluating the expression, and as such filter arguments for CALCULATE replace all
existing filters over the same columns. The new context effected by the filter argument
for CALCULATE affects only existing filters on columns mentioned as part of the filter
argument. Filters on columns other than those mentioned in the arguments of
CALCULATE or other related functions remain in effect and unaltered.
The KEEPFILTERS function allows you to modify this behavior. When you use
KEEPFILTERS, any existing filters in the current context are compared with the columns in
the filter arguments, and the intersection of those arguments is used as the context for
evaluating the expression. The net effect over any one column is that both sets of
arguments apply: both the filter arguments used in CALCULATE and the filters in the
arguments of the KEEPFILTER function. In other words, whereas CALCULATE filters
replace the current context, KEEPFILTERS adds filters to the current context.
Example
Description
The following example takes you through some common scenarios that demonstrate use
of the KEEPFILTERS function as part of a CALCULATE or CALCULATETABLE formula.
The first three expressions obtain simple data to be used for comparisons:
• Internet Sales for the state of Washington.
• Internet Sales for the states of Washington and Oregon (both states combined).
• Internet Sales for the state of Washington and the province of British Columbia (both
regions combined).
The fourth expression calculates Internet Sales for Washington and Oregon, while the
filter for Washington and British Columbia is applied.
The next expression calculates Internet Sales for Washington and Oregon but uses
KEEPFILTERS; the filter for Washington and British Columbia is part of the prior context.
Code
EVALUATE ROW(
"$$ in WA"
, CALCULATE('Internet Sales'[Internet Total Sales]
, 'Geography'[State Province Code]="WA"
)
, "$$ in WA and OR"
, CALCULATE('Internet Sales'[Internet Total Sales]
, 'Geography'[State Province Code]="WA"
149
|| 'Geography'[State Province Code]="OR"
)
, "$$ in WA and BC"
, CALCULATE('Internet Sales'[Internet Total Sales]
, 'Geography'[State Province Code]="WA"
|| 'Geography'[State Province Code]="BC"
)
, "$$ in WA and OR ??"
, CALCULATE(
CALCULATE('Internet Sales'[Internet Total Sales]
,'Geography'[State Province Code]="WA"
|| 'Geography'[State Province Code]="OR"
)
, 'Geography'[State Province Code]="WA"
|| 'Geography'[State Province Code]="BC"
)
, "$$ in WA !!"
, CALCULATE(
CALCULATE('Internet Sales'[Internet Total Sales]
, KEEPFILTERS('Geography'[State Province Code]="WA"
|| 'Geography'[State Province Code]="OR"
)
)
, 'Geography'[State Province Code]="WA"
|| 'Geography'[State Province Code]="BC"
)
)
Comments
When this expression is evaluated against the sample database AdventureWorks DW
Tabular 2012, the following results are obtained.
150
Column Value
Note
The above results were formatted to a table, instead of a single row, for
educational purposes.
First, examine the expression, [$$ in WA and OR ??]. You might wonder how this
formula could return the value for sales in Washington and Oregon, since the outer
CALCULATE expression includes a filter for Washington and British Columbia. The answer
is that the default behavior of CALCULATE overrides the outer filters in 'Geography'[State
Province Code] and substitutes its own filter arguments, because the filters apply to the
same column.
Next, examine the expression, [$$ in WA !!]. You might wonder how this formula could
return the value for sales in Washington and nothing else, since the argument filter
includes Oregon and the outer CALCULATE expression includes a filter in Washington
and British Columbia. The answer is that KEEPFILTERS modifies the default behavior of
CALCULATE and adds an additional filter. Because the intersection of filters is used, now
the outer filter 'Geography'[State Province Code]="WA" || 'Geography'[State
Province Code]="BC") is added to the filter argument 'Geography'[State Province
Code]="WA" || 'Geography'[State Province Code]="OR",. Because both filters apply
to the same column, the resulting filter 'Geography'[State Province Code]="WA" is
the filter that is applied when evaluating the expression.
See Also
Filter and value functions
CALCULATE
CALCULATETABLE
RELATED Function
Returns a related value from another table.
Syntax
RELATED(<column>)
151
Parameters
Term Definition
Return Value
A single value that is related to the current row.
Remarks
The RELATED function requires that a relationship exists between the current table and
the table with related information. You specify the column that contains the data that
you want, and the function follows an existing many-to-one relationship to fetch the
value from the specified column in the related table.
If a relationship does not exist, you must create a relationship. For more information,
see Creating a Relationship.
When the RELATED function performs a lookup, it examines all values in the specified
table regardless of any filters that may have been applied.
Note
The RELATED function needs a row context; therefore, it can only be used in
calculated column expression, where the current row context is unambiguous, or
as a nested function in an expression that uses a table scanning function. A table
scanning function, such as SUMX, gets the value of the current row value and
then scans another table for instances of that value.
Example
Description
In the following example, the measure Non USA Internet Sales is created to produce a
sales report that excludes sales in the United States. In order to create the measure, the
InternetSales_USD table must be filtered to exclude all sales that belong to the United
States in the SalesTerritory table. The United States, as a country, appears 5 times in the
SalesTerritory table; once for each of the following regions: Northwest, Northeast,
Central, Southwest, and Southeast.
The first approach to filter the Internet Sales, in order to create the measure, could be to
add a filter expression like the following:
FILTER('InternetSales_USD', 'InternetSales_USD'[SalesTerritoryKey]<>1
&& 'InternetSales_USD'[SalesTerritoryKey]<>2 &&
'InternetSales_USD'[SalesTerritoryKey]<>3 &&
'InternetSales_USD'[SalesTerritoryKey]<>4 &&
'InternetSales_USD'[SalesTerritoryKey]<>5)
152
However, this approach is counterintuitive, prone to typing errors, and might not work if
any of the existing regions is split in the future.
A better approach would be to use the existing relationship between InternetSales_USD
and SalesTerritory and explicitly state that the country must be different from the United
States. To do so, create a filter expression like the following:
FILTER( 'InternetSales_USD',
RELATED('SalesTerritory'[SalesTerritoryCountry])<>"United States")
This expression uses the RELATED function to lookup the country value in the
SalesTerritory table, starting with the value of the key column, SalesTerritoryKey, in the
InternetSales_USD table. The result of the lookup is used by the filter function to
determine if the InternetSales_USD row is filtered or not.
Note
If the example does not work, you might need to create a relationship between
the tables. For more information, see Relationships Between Tables.
Code
= SUMX(FILTER( 'InternetSales_USD'
, RELATED('SalesTerritory'[SalesTerritoryCountry])
<>"United States"
)
,'InternetSales_USD'[SalesAmount_USD])
Comments
The following table shows only totals for each region, to prove that the filter expression
in the measure, Non USA Internet Sales, works as intended.
The following table shows the final report that you might get if you used this measure in
a PivotTable:
153
Non USA Column Labels
Internet Sales
See Also
RELATEDTABLE
Filter and value functions
Relationships between tables
RELATEDTABLE Function
Evaluates a table expression in a context modified by the given filters.
Syntax
RELATEDTABLE(<tableName>)
Parameters
Term Definition
Return Value
A table of values.
Remarks
The RELATEDTETABLE function changes the context in which the data is filtered, and
evaluates the expression in the new context that you specify.
This function is a shortcut for CALCULATETABLE function with no logical expression.
154
Example
Description
The following example uses the RELATEDTABLE function to create a calculated column
with the Internet Sales in the Product Category table.
The following table shows the results of using the code shown here.
Code
= SUMX( RELATEDTABLE('InternetSales_USD')
, [SalesAmount_USD])
See Also
CALCULATETABLE Function (DAX)
Filter and value functions
Relationships between tables
USERELATIONSHIP Function
Specifies the relationship to be used in a specific calculation as the one that exists
between columnName1 and columnName2.
Syntax
USERELATIONSHIP(<columnName1>,<columnName2>)
Parameters
Parameter Description
155
order the function will swap them
before using them. This argument
cannot be an expression.
Return Value
The function returns no value; the function only enables the indicated relationship for the
duration of the calculation.
Remarks
1. USERELATIONSHIP can only be used in functions that take a filter as an argument,
for example: CALCULATE, CALCULATETABLE, CLOSINGBALANCEMONTH,
CLOSINGBALANCEQUARTER, CLOSINGBALANCEYEAR,
OPENINGBALANCEMONTH, OPENINGBALANCEQUARTER,
OPENINGBALANCEYEAR, TOTALMTD, TOTALQTD and TOTALYTD functions.
2. USERELATIONSHIP uses existing relationships in the model, identifying relationships
by their ending point columns.
3. In USERELATIONSHIP, the status of a relationship is not important; that is, whether
the relationship is active or not does not affect the usage of the function. Even if the
relationship is inactive, it will be used and overrides any other active relationships
that might be present in the model but not mentioned in the function arguments.
4. An error is returned if any of the columns named as an argument is not part of a
relationship or the arguments belong to different relationships.
5. If multiple relationships are needed to join table A to table B in a calculation, each
relationship must be indicated in a different USERELATIONSHIP function.
6. If CALCULATE expressions are nested, and more than one CALCULATE expression
contains a USERELATIONSHIP function, then the innermost USERELATIONSHIP is the
one that prevails in case of a conflict or ambiguity.
7. Up to 10 USERELATIONSHIP functions can be nested; however, your expression
might have a deeper level of nesting, ie. the following sample expression is nested 3
levels deep but only 2 for USEREALTIONSHIP: =CALCULATE(CALCULATE(
CALCULATE( <anyExpression>, USERELATIONSHIP( t1[colA], t2[colB])),
t99[colZ]=999), USERELATIONSHIP( t1[colA], t2[colA])).
156
Example
Description
The following sample shows how to override the default, active, relationship between
InternetSales and DateTime tables. The default relationship exists between the
OrderDate column, in the InternetSales table, and the Date column, in the DateTime
table.
To calculate the sum of internet sales and allow slicing by ShippingDate instead of the
traditional OrderDate you need to create a measure, [InternetSales by ShippingDate]
using the following expression:
Code
=CALCULATE(SUM(InternetSales[SalesAmount]),
USERELATIONSHIP(InternetSales[ShippingDate], DateTime[Date]))
Comments
In PowerPivot: drag your new measure to the Values area in the right pane, drag the
InternetSales[ShippingDate] column to the Row Labels area; you now have Internet
Sales sliced by shipping date instead of by order date as is usually shown in these
examples.
For this example to work the relationships between InternetSales[ShipmentDate] and
DateTime[Date] must exist and should not be the active relationship; also, the
relationship between InternetSales[OrderDate] and DateTime[Date] should exist and
should be the active relationship.
VALUES Function
Returns a one-column table that contains the distinct values from the specified column.
In other words, duplicate values are removed and only unique values are returned.
Note
This function cannot be used to return values into a cell or column on a
worksheet; rather, you use it as an intermediate function, nested in a formula, to
get a list of distinct values that can be counted, or used to filter or sum other
values.
Syntax
VALUES(<column>)
Parameters
Term Definition
157
Term Definition
to be returned.
Return Value
A column of unique values.
Remarks
When you use the VALUES function in a context that has been filtered, such as in a
PivotTable, the unique values returned by VALUES are affected by the filter. For example,
if you filter by Region, and return a list of the values for City, the list will include only
those cities in the regions permitted by the filter. To return all of the cities, regardless of
existing filters, you must use the ALL function to remove filters from the table. The
second example demonstrates use of ALL with VALUES.
Related Functions
In most scenarios, the results of the VALUES function are identical to those of the
DISTINCT function. Both functions remove duplicates and return a list of the possible
values in the specified column. However, the VALUES function can also return an
Unknown member. This unknown value is useful in cases where you are looking up
distinct values from a related table, but a value used in the relationship is missing from
one table. In database terminology, this is termed a violation of referential integrity. Such
mismatches in data can easily occur when one table is being updated and the related
table is not.
The following table summarizes the mismatch between data that can occur in two
related tables when referential integrity is not preserved.
If you used the DISTINCT function to return a list of dates from the PivotTable containing
these tables, only two dates would be returned. However, if you use the VALUES
function, the function returns the two dates plus an additional blank member. Also, any
row from the MySales table that does not have a matching date in the MyOrders table
will be "matched" to this unknown member.
Example
Description
158
The following formula counts the number of unique invoices (sales orders), and produces
the following results when used in a report that includes the Product Category Names:
Accessories 18,208
Bikes 15,205
Clothing 7,461
Grand Total 27,659
Code
=COUNTROWS(VALUES('InternetSales_USD'[SalesOrderNumber]))
See Also
FILTER
COUNTROWS
Filter and value functions
Information Functions
An information function looks at the cell or row that is provided as an argument and tells
you whether the value matches the expected type. For example, the ISERROR function
returns TRUE if the value that you reference contains an error.
In this Section
CONTAINS Function
ISBLANK Function
ISERROR Function
ISLOGICAL Function
ISNONTEXT Function
ISNUMBER Function
ISTEXT Function
LOOKUPVALUE Function
PATH Function
PATHCONTAINS Function
PATHITEM Function
PATHITEMREVERSE Function
PATHLENGTH Function
159
See Also
Function Reference (DAX)
CONTAINS Function
Returns true if values for all referred columns exist, or are contained, in those columns;
otherwise, the function returns false.
Syntax
CONTAINS(<table>, <columnName>, <value>[, <columnName>, <value>]…)
Parameters
Parameter Description
Return Value
A value of TRUE if each specified value can be found in the corresponding columnName,
or are contained, in those columns; otherwise, the function returns FALSE.
Remarks
• The arguments columnName and value must come in pairs; otherwise an error is
returned.
• columnName must belong to the specified table, or to a table that is related to table.
• If columnName refers to a column in a related table then it must be fully qualified;
otherwise, an error is returned.
Example
Description
The following example creates a calculated measure that tells you whether there were
any Internet sales of the product 214 and to customer 11185 at the same time.
Code
160
=CONTAINS(InternetSales, [ProductKey], 214, [CustomerKey], 11185)
Comments
CUSTOMDATA Function
Returns the content of the CustomData property in the connection string.
Syntax
CUSTOMDATA()
Return Value
The content of the CustomData property in the connection string.
Blank, if CustomData property was not defined at connection time.
Exceptions
Remarks
Example
Description
The following DAX code verifies if the CustomData property was set to "OK".
Code
=IF(CUSTOMDATA()="OK", "Correct Custom data in connection string", "No
custom data in connection string property or unexpected value")
Comments
ISBLANK Function
Checks whether a value is blank, and returns TRUE or FALSE.
Syntax
ISBLANK(<value>)
Parameters
Term Definition
161
Return Value
A Boolean value of TRUE if the value is blank; otherwise FALSE.
Example
Description
This formula computes the increase or decrease ratio in sales compared to the previous
year. The example uses the IF function to check the value for the previous year's sales in
order to avoid a divide by zero error.
Row Labels Total Sales Total Sales Previous Year Sales to Previous
Year Ratio
2005 $10,209,985.08
2006 $28,553,348.43 $10,209,985.08 179.66%
2007 $39,248,847.52 $28,553,348.43 37.46%
2008 $24,542,444.68 $39,248,847.52 -37.47%
Grand Total $102,554,625.71
Code
//Sales to Previous Year Ratio
=IF( ISBLANK('CalculatedMeasures'[PreviousYearTotalSales])
, BLANK()
, ( 'CalculatedMeasures'[Total Sales]-
'CalculatedMeasures'[PreviousYearTotalSales] )
/'CalculatedMeasures'[PreviousYearTotalSales])
See Also
Information functions (DAX)
ISERROR Function
Checks whether a value is an error, and returns TRUE or FALSE.
Syntax
ISERROR(<value>)
Parameters
162
Term Definition
Return Value
A Boolean value of TRUE if the value is an error; otherwise FALSE.
Example
Description
The following example calculates the ratio of total Internet sales to total reseller sales.
The ISERROR function is used to check for errors, such as division by zero. If there is an
error a blank is returned, otherwise the ratio is returned.
Code
= IF( ISERROR(
SUM('ResellerSales_USD'[SalesAmount_USD])
/SUM('InternetSales_USD'[SalesAmount_USD])
)
, BLANK()
, SUM('ResellerSales_USD'[SalesAmount_USD])
/SUM('InternetSales_USD'[SalesAmount_USD])
)
See Also
Information functions (DAX)
IFERROR
IF
ISLOGICAL Function
Checks whether a value is a logical value, (TRUE or FALSE), and returns TRUE or FALSE.
Syntax
ISLOGICAL(<value>)
Parameters
Term Definition
163
Property Value/Return Value
TRUE if the value is a logical value; FALSE if any value other than TRUE OR FALSE.
Example
Description
The following three samples show the behavior of ISLOGICAL.
Code
//RETURNS: Is Boolean type or Logical
=IF(ISLOGICAL(true), "Is Boolean type or Logical", "Is different type")
See Also
Information functions (DAX)
ISNONTEXT Function
Checks if a value is not text (blank cells are not text), and returns TRUE or FALSE.
Syntax
ISNONTEXT(<value>)
Parameters
Term Definition
Return Value
TRUE if the value is not text or blank; FALSE if the value is text.
Remarks
An empty string is considered text.
Example
164
Description
The following examples show the behavior of the ISNONTEXT function.
Code
//RETURNS: Is Non-Text
=IF(ISNONTEXT(1), "Is Non-Text", "Is Text")
//RETURNS: Is Non-Text
=IF(ISNONTEXT(BLANK()), "Is Non-Text", "Is Text")
//RETURNS: Is Text
=IF(ISNONTEXT(""), "Is Non-Text", "Is Text")
See Also
Information functions (DAX)
ISNUMBER Function
Checks whether a value is a number, and returns TRUE or FALSE.
Syntax
ISNUMBER(<value>)
Parameters
Term Definition
165
//RETURNS: Is number
=IF(ISNUMBER(3.1E-1),"Is number", "Is Not number")
ISTEXT Function
Checks if a value is text, and returns TRUE or FALSE.
Syntax
ISTEXT(<value>)
Parameters
Term Definition
//RETURNS: Is Text
=IF(ISTEXT(""), "Is Text", "Is Non-Text")
//RETURNS: Is Non-Text
=IF(ISTEXT(1), "Is Text", "Is Non-Text")
166
//RETURNS: Is Non-Text
=IF(ISTEXT(BLANK()), "Is Text", "Is Non-Text")
See Also
Information functions (DAX)
LOOKUPVALUE Function
Returns the value in result_columnName for the row that meets all criteria specified by
search_columnName and search_value.
Syntax
LOOKUPVALUE( <result_columnName>, <search_columnName>, <search_value>[,
<search_columnName>, <search_value>]…)
Parameters
Parameter Description
Return Value
The value of result_column at the row where all pairs of search_column and search_value
have a match.
If there is no match that satisfies all the search values, a BLANK is returned. In other
words, the function will not return a lookup value if only some of the criteria match.
167
If multiple rows match the search values and in all cases result_column values are
identical then that value is returned. However, if result_column returns different values an
error is returned.
Remarks
Example
Description
The following example returns the SafetyStocklLevel for the bike model "Mountain-400-
W Silver, 46".
Code
=LOOKUPVALUE(Product[SafetyStockLevel], [ProductName], " Mountain-400-W
Silver, 46")
Comments
PATH Function
Returns a delimited text string with the identifiers of all the parents of the current
identifier, starting with the oldest and continuing until current.
Syntax
PATH(<ID_columnName>, <parent_columnName>)
Parameters
Parameter Description
168
be the same data type as the value
in ID_columnName.
Return Value
A delimited text string containing the identifiers of all the parents to the current
identifier.
Remarks
This function is used in tables that have some kind of internal hierarchy, to return the
items that are related to the current row value. For example, in an Employees table that
contains employees, the managers of employees, and the managers of the managers,
you can return the path that connects an employee to his or her manager.
The path is not constrained to a single level of parent-child relationships; it can return
related rows that are several levels up from the specified starting row.
The delimiter used to separate the ascendants is the vertical bar, '|'.
The values in ID_columnName and parent_columnName must have the same data type,
text or integer.
Values in parent_columnName must be present in ID_columnName. That is, you cannot
look up a parent if there is no value at the child level.
If parent_columnName is BLANK then PATH() returns ID_columnName value. In other
words, if you look for the manager of an employee but the parent_columnName
column has no data, the PATH function returns just the employee ID.
If ID_columnName has duplicates and parent_columnName is the same for those
duplicates then PATH() returns the common parent_columnName value; however, if
parent_columnName value is different for those duplicates then PATH() returns an
error. In other words, if you have two listings for the same employee ID and they
have the same manager ID, the PATH function returns the ID for that manager.
However, if there are two identical employee IDs that have different manager IDs, the
PATH function returns an error.
If ID_columnName is BLANK then PATH() returns BLANK.
If ID_columnName contains a vertical bar '|' then PATH() returns an error.
This DAX function is not supported for use in DirectQuery mode. For more information
about limitations in DirectQuery models,
see http://go.microsoft.com/fwlink/?LinkId=219172.
Example
Description
The following example creates a calculated column that lists all the managers for each
employee.
Code
169
=PATH(Employee[EmployeeKey], Employee[ParentEmployeeKey])
Comments
PATHCONTAINS Function
Returns TRUE if the specified item exists within the specified path.
Syntax
PATHCONTAINS(<path>, <item>)
Parameters
Parameter Description
Return Value
A value of TRUE if item exists in path; otherwise FALSE.
Remarks
If item is an integer number it is converted to text and then the function is evaluated. If
conversion fails then the function returns an error.
This DAX function is not supported for use in DirectQuery mode. For more information
about limitations in DirectQuery models,
see http://go.microsoft.com/fwlink/?LinkId=219172.
Example
Description
The following example creates a calculated column that takes a manager ID and checks a
set of employees. If the manager ID is among the list of managers returned by the PATH
function, the PATHCONTAINS function returns true; otherwise it returns false.
Code
=PATHCONTAINS(PATH(Employee[EmployeeKey], Employee[ParentEmployeeKey]),
"23")
Comments
170
PATHITEM Function
Returns the item at the specified position from a string resulting from evaluation of a
PATH function. Positions are counted from left to right.
Syntax
PATHITEM(<path>, <position>[, <type>])
Parameters
Parameter Description
Return Value
The identifier returned by the PATH function at the specified position in the list of
identifiers. Items returned by the PATH function are ordered by most distant to current.
Remarks
This function can be used to return a specific level from a hierarchy returned by a PATH
function. For example, you could return just the skip-level managers for all
employees.
If you specify a number for position that is less than one (1) or greater than the number
of elements in path, the PATHITEM function returns BLANK
171
If type is not a valid enumeration element an error is returned.
This DAX function is not supported for use in DirectQuery mode. For more information
about limitations in DirectQuery models,
see http://go.microsoft.com/fwlink/?LinkId=219172.
Example
Description
The following example returns the third tier manager of the current employee; it takes
the employee and manager IDs as the input to a PATH function that returns a string with
the hierarchy of parents to current employee. From that string PATHITEM returns the
third entry as an integer.
Code
=PATHITEM(PATH(Employee[EmployeeKey], Employee[ParentEmployeeKey]), 3,
1)
Comments
PATHITEMREVERSE Function
Returns the item at the specified position from a string resulting from evaluation of a
PATH function. Positions are counted backwards from right to left.
Syntax
PATHITEMREVERSE(<path>, <position>[, <type>])
Parameters
Parameter Description
172
returned
with the
data type of
text.
(default)
INTEGER 1 Results are
returned
with the
data type of
integer.
Return Value
The n-position ascendant in the given path, counting from current to the oldest.
Remarks
• This function can be used to get an individual item from a hierarchy resulting from a
PATH function.
• This function reverses the standard order of the hierarchy, so that closest items are
listed first, For example, if the PATh function returns a list of managers above an
employee in a hierarchy, the PATHITEMREVERSE function returns the employee’s
immediate manager in position 2 because position 1 contains the employee’s id.
• If the number specified for position is less than one (1) or greater than the number of
elements in path, the PATHITEM function returns BLANK.
• If type is not a valid enumeration element an error is returned.
This DAX function is not supported for use in DirectQuery mode. For more information
about limitations in DirectQuery models,
see http://go.microsoft.com/fwlink/?LinkId=219172.
Example
Description
The following example takes an employee ID column as the input to a PATH function,
and reverses the list of grandparent elements that are returned. The position specified is
3 and the return type is 1; therefore, the PATHITEMREVERSE function returns an integer
representing the manager two levels up from the employee.
Code
=PATHITEMREVERSE(PATH(Employee[EmployeeKey],
Employee[ParentEmployeeKey]), 3, 1)
Comments
173
PATHLENGTH Function
Returns the number of parents to the specified item in a given PATH result, including
self.
Syntax
PATHLENGTH(<path>)
Parameters
Parameter Description
Return Value
The number of items that are parents to the specified item in a given PATH result,
including the specified item.
Remarks
This DAX function is not supported for use in DirectQuery mode. For more information
about limitations in DirectQuery models,
see http://go.microsoft.com/fwlink/?LinkId=219172.
Example
Description
The following example takes an employee ID as input to a PATH function and returns a
list of the managers above that employee in the hierarchy, The PATHLENGTH function
takes that result and counts the different levels of employees and managers, including
the employee you started with.
Code
=PATHLENGTH(PATH(Employee[EmployeeKey], Employee[ParentEmployeeKey]))
Comments
USERNAME Function
Returns the domain name and username from the credentials given to the system at
connection time
Syntax
USERNAME()
Parameters
174
Return Value
The username from the credentials given to the system at connection time
Exceptions
Remarks
Under Windows authentication, the returned string has the structure: <domain-
name>\<user-name>
Example
Description
The following code verifies if the user login is part of the UsersTable.
Code
=IF(CONTAINS(UsersTable,UsersTable[login], USERNAME()), "Allowed",
BLANK())
Comments
Logical Functions
Logical functions act upon an expression to return information about the values or sets
in the expression. For example, you can use the IF function to check the result of an
expression and create conditional results.
In this Section
AND Function
FALSE Function
IF Function
IFERROR Function
NOT Function
OR Function
SWITCH Function
TRUE Function
Reference
Using DAX
Basic DAX Syntax
Related Sections
Date and Time Functions (DAX)
Aggregation Functions (DAX)
175
Logical Functions (DAX)
Filter and Value Functions (DAX)
Math and Trigonometric Functions (DAX)
See Also
Getting Started with Data Analysis Expressions (DAX)
AND Function
Checks whether both arguments are TRUE, and returns TRUE if both arguments are
TRUE. Otherwise returns false.
Syntax
AND(<logical1>,<logical2>)
Parameters
Term Definition
Return Value
Returns true or false depending on the combination of values that you test.
Remarks
The AND function in DAX accepts only two (2) arguments. If you need to perform an
AND operation on multiple expressions, you can create a series of calculations or, better,
use the AND operator (&&) to join all of them in a simpler expression.
Example
Description
The following formula shows the syntax of the AND function.
Code
=IF(AND(10 > 9, -10 < -1), "All true", "One or more false"
Comments
Because both conditions, passed as arguments, to the AND function are true, the
formula returns "All True".
Example
Description
The following sample uses the AND function with nested formulas to compare two sets
of calculations at the same time. For each product category, the formula determines if
176
the current year sales and previous year sales of the Internet channel are larger than the
Reseller channel for the same periods. If both conditions are true, for each category the
formula returns the value, "Internet hit".
177
AND function Column
Labels
Locks
Mountain Bikes
Mountain
Frames
Panniers
Pedals
Pumps
Road Bikes
Road Frames
Saddles
Shorts
Socks
Tights
Tires and Tubes Internet Hit
Touring Bikes
Touring Frames
Vests
Wheels
Grand Total
Code
= IF( AND( SUM( 'InternetSales_USD'[SalesAmount_USD])
>SUM('ResellerSales_USD'[SalesAmount_USD])
, CALCULATE(SUM('InternetSales_USD'[SalesAmount_USD]),
PREVIOUSYEAR('DateTime'[DateKey] ))
>CALCULATE(SUM('ResellerSales_USD'[SalesAmount_USD]),
PREVIOUSYEAR('DateTime'[DateKey] ))
)
178
, "Internet Hit"
, ""
)
Comments
See Also
Logical Functions
FALSE Function
Returns the logical value FALSE.
Syntax
FALSE()
Return Value
Always FALSE.
Remarks
The word FALSE is also interpreted as the logical value FALSE.
Example
Description
The formula returns the logical value FALSE when the value in the column,
'InternetSales_USD'[SalesAmount_USD], is less than or equal to 200000.
The following table shows the results when the example formula is used with
'ProductCategory'[ProductCategoryName] in Row Labels and 'DateTime'[CalendarYear]
in Column Labels.
True-False Column
Labels
179
Code
=IF(SUM('InternetSales_USD'[SalesAmount_USD]) >200000, TRUE(), false())
See Also
TRUE
NOT
IF
Function Reference
IF Function
Checks if a condition provided as the first argument is met. Returns one value if the
condition is TRUE, and returns another value if the condition is FALSE.
Syntax
IF(logical_test>,<value_if_true>, value_if_false)
Parameters
Term Definition
Return Value
Any type of value that can be returned by an expression.
Remarks
If the value of value_if_true or value_if_false is omitted, IF treats it as an empty string
value ("").
If the value referenced in the expression is a column, IF returns the value that
corresponds to the current row.
The IF function attempts to return a single data type in a column. Therefore, if the values
returned by value_if_true and value_if_false are of different data types, the IF function
will implicitly convert data types to accommodate both values in the column. For
example, the formula IF(<condition>,TRUE(),0) returns a column of ones and zeros
180
and the results can be summed, but the formula IF(<condition>,TRUE(),FALSE())
returns only logical values. For more information about implicit data type conversion,
see Data Types in DAX.
Example
Description
The following example uses nested IF functions that evaluate the number in the column,
Calls, from the table FactCallCenter in Adventure Works DW Multidimensional 2012 .
The function assigns a label as follows: low if the number of calls is less than 200,
medium if the number of calls is less than 300 but not less than 200, and high for all
other values.
Code
=IF([Calls]<200,"low",IF([Calls]<300,"medium","high"))
Example
Description
The following example gets a list of cities that contain potential customers in the
California area by using columns from the table ProspectiveBuyer in Adventure Works
DW Multidimensional 2012 . Because the list is meant to plan for a campaign that will
target married people or people with children at home, the condition in the IF function
checks for the value of the columns [MaritalStatus] and [NumberChildrenAtHome], and
outputs the city if either condition is met and if the customer is in California. Otherwise, it
outputs the empty string.
Code
=IF([StateProvinceCode]= "CA" && ([MaritalStatus] = "M" ||
[NumberChildrenAtHome] >1),[City])
Comments
Note that parentheses are used to control the order in which the AND (&&) and OR (||)
operators are used. Also note that no value has been specified for value_if_false.
Therefore, the function returns the default, which is an empty string.
See Also
TRUE
FALSE
NOT
IF
Function Reference
IFERROR Function
Evaluates an expression and returns a specified value if the expression returns an error;
otherwise returns the value of the expression itself.
181
Syntax
IFERROR(value, value_if_error)
Parameters
Term Definition
Return Value
A scalar of the same type as value
Exceptions
Remarks
You can use the IFERROR function to trap and handle errors in an expression.
If value or value_if_error is an empty cell, IFERROR treats it as an empty string value ("").
The IFERROR function is based on the IF function, and uses the same error messages, but
has fewer arguments. The relationship between the IFERROR function and the IF function
as follows:
IFERROR(A,B) := IF(ISERROR(A), B, A)
Note that the values that are returned for A and B must be of the same data type;
therefore, the column or expression used for value and the value returned for
value_if_error must be the same data type.
Example
Description
The following example returns 9999 if the expression 25/0 evaluates to an error. If the
expression returns a value other than error, that value is passed to the invoking
expression.
Code
=IFERROR(25/0,9999)
Comments
See Also
Logical Functions
NOT Function
Changes FALSE to TRUE, or TRUE to FALSE.
182
Syntax
NOT(<logical>)
Parameters
Term Definition
Return Value
TRUE OR FALSE.
Example
Description
The following example retrieves values from the calculated column that was created to
illustrate the IF function. For that example, the calculated column was named using the
default name, Calculated Column1, and contains the following formula:
=IF([Orders]<300,"true","false")
The formula checks the value in the column, [Orders], and returns "true" if the number of
orders is under 300.
Now create a new calculated column, Calculated Column2, and type the following
formula.
Code
=NOT([CalculatedColumn1])
Comments
For each row in Calculated Column1, the values "true" and "false" are interpreted as the
logical values TRUE or FALSE, and the NOT function returns the logical opposite of that
value.
See Also
TRUE
FALSE
IF
Function Reference
OR Function
Checks whether one of the arguments is TRUE to return TRUE. The function returns
FALSE if both arguments are FALSE.
183
Syntax
OR(<logical1>,<logical2>)
Parameters
Term Definition
Return Value
A Boolean value. The value is TRUE if any of the two arguments is TRUE; the value is
FALSE if both the arguments are FALSE.
Remarks
The OR function in DAX accepts only two (2) arguments. If you need to perform an OR
operation on multiple expressions, you can create a series of calculations or, better, use
the OR operator (||) to join all of them in a simpler expression.
The function evaluates the arguments until the first TRUE argument, then returns TRUE.
Example
Description
The following example shows how to use the OR function to obtain the sales people that
belong to the Circle of Excellence. The Circle of Excellence recognizes those who have
achieved more than a million dollars in Touring Bikes sales or sales of over two and a half
million dollars in 2007.
SalesPersonFlag True
OR function Column
Labels
Row Labels 2005 2006 2007 2008 Grand
Total
Abbas, Syed E
Alberts, Amy
E
Ansman-
Wolfe, Pamela
O
184
SalesPersonFlag True
Code
185
IF( OR( CALCULATE(SUM('ResellerSales_USD'[SalesAmount_USD]),
'ProductSubcategory'[ProductSubcategoryName]="Touring Bikes") > 1000000
, CALCULATE(SUM('ResellerSales_USD'[SalesAmount_USD]),
'DateTime'[CalendarYear]=2007) > 2500000
)
, "Circle of Excellence"
, ""
)
Comments
See Also
Logical functions
SWITCH Function
Evaluates an expression against a list of values and returns one of multiple possible
result expressions.
Syntax
SWITCH(<expression>, <value>, <result>[, <value>, <result>]…[, <else>])
Parameters
Parameter Description
186
Return Value
A scalar value coming from one of the result expressions, if there was a match with value,
or from the else expression, if there was no match with any value.
Exceptions
Remarks
All result expressions and the else expression must be of the same data type.
Example
Description
The following example creates a calculated column of month names.
Code
=SWITCH([Month], 1, "January", 2, "February", 3, "March", 4, "April"
, 5, "May", 6, "June", 7, "July", 8, "August"
, 9, "September", 10, "October", 11, "November", 12,
"December"
, "Unknown month number" )
Comments
TRUE Function
Returns the logical value TRUE.
Syntax
TRUE()
Return Value
Always TRUE.
Remarks
The word TRUE is also interpreted as the logical value TRUE.
Example
Description
The formula returns the logical value TRUE when the value in the column,
'InternetSales_USD'[SalesAmount_USD], is greater than 200000.
The following table shows the results when the example formula is used in a PivotTable,
with 'ProductCategory'[ProductCategoryName] in Row Labels and
'DateTime'[CalendarYear] in Column Labels.
187
True-False Column
Labels
Code
= IF(SUM('InternetSales_USD'[SalesAmount_USD]) >200000, TRUE(),
false())
See Also
FALSE
NOT
IF
Function Reference
188
INT Function
ISO.CEILING Function
LN Function
LOG Function
LOG10 Function
MOD Function
MROUND Function
PI Function
POWER Function
QUOTIENT Function
RAND Function (DAX)
RANDBETWEEN Function (DAX)
ROUND Function
ROUNDDOWN Function
ROUNDUP Function
SIGN Function
SQRT Function
SUM Function
SUMX Function
TRUNC Function
Reference
Using DAX
Basic DAX Syntax
Related Sections
Date and Time Functions (DAX)
Aggregation Functions (DAX)
Logical Functions (DAX)
Filter and Value Functions (DAX)
Math and Trigonometric Functions (DAX)
See Also
Getting Started with Data Analysis Expressions (DAX)
ABS Function
Returns the absolute value of a number.
189
Syntax
ABS(<number>)
Parameters
Term Definition
Return Value
A decimal number.
Remarks
The absolute value of a number is a decimal number, whole or decimal, without its sign.
You can use the ABS function to ensure that only non-negative numbers are returned
from expressions when nested in functions that require a positive number.
Example
Description
The following example returns the absolute value of the difference between the list price
and the dealer price, which you might use in a new calculated column, DealerMarkup.
Code
=ABS([DealerPrice]-[ListPrice])
See Also
Scalar math and trig functions
SIGN function
CEILING Function
Rounds a number up, to the nearest integer or to the nearest multiple of significance.
Syntax
CEILING(<number>, <significance>)
Parameters
Term Definition
Return Value
A number rounded as specified.
Remarks
There are two CEILING functions in DAX, with the following differences:
• The CEILING function emulates the behavior of the CEILING function in Excel.
• The ISO.CEILING function follows the ISO-defined behavior for determining the
ceiling value.
The two functions return the same value for positive numbers, but different values for
negative numbers. When using a positive multiple of significance, both CEILING and
ISO.CEILING round negative numbers upward (toward positive infinity). When using a
negative multiple of significance, CEILING rounds negative numbers downward (toward
negative infinity), while ISO.CEILING rounds negative numbers upward (toward positive
infinity).
The return type is usually of the same type of the significant argument, with the
following exceptions:
• If the number argument type is currency, the return type is currency.
• If the significance argument type is Boolean, the return type is integer.
• If the significance argument type is non-numeric, the return type is real.
Example
Description
The following formula returns 4.45. This might be useful if you want to avoid using
smaller units in your pricing. If an existing product is priced at $4.42, you can use
CEILING to round prices up to the nearest unit of five cents.
Code
=CEILING(4.42,0.05)
Example
Description
The following formula returns similar results as the previous example, but uses numeric
values stored in the column, ProductPrice.
Code
=CEILING([ProductPrice],0.05)
191
See Also
Math and Trig functions
FLOOR function
ISO.CEILING Function (DAX)
ROUNDUP function
CURRENCY Function
Evaluates the argument and returns the result as currency data type.
Syntax
CURRENCY(<value>)
Parameters
Parameter Description
Return Value
The value of the expression evaluated and returned as a currency type value.
Remarks
• The CURRENCY function rounds up the 5th significant decimal, in value, to return the
4th decimal digit; rounding up occurs if the 5th significant decimal is equal or larger
than 5. For example, if value is 3.6666666666666 then converting to currency returns
$3.6667; however, if value is 3.0123456789 then converting to currency returns
$3.0123.
• If the data type of the expression is TrueFalse then CURRENCY( <TrueFalse>) will
return $1.0000 for True values and $0.0000 for False values.
• If the data type of the expression is Text then CURRENCY(<Text>) will try to convert
text to a number; if conversion succeeds the number will be converted to currency,
otherwise an error is returned.
• If the data type of the expression is DateTime then CURRENCY(<DateTime>) will
convert the datetime value to a number and that number to currency. DateTime
values have an integer part that represents the number of days between the given
date and 1900-03-01 and a fraction that represents the fraction of a day (where 12
hours or noon is 0.5 day). If the value of the expression is not a proper DateTime
value an error is returned.
192
Example
Description
Convert number 1234.56 to currency data type.
Code
=CURRENCY(1234.56)
Comments
Returns the value $1234.5600.
EXP Function
Returns raised to the power of a given number. The constant e equals
2.71828182845904, the base of the natural logarithm.
Syntax
EXP(<number>)
Parameters
Term Definition
Return Value
A decimal number.
Exceptions
Remarks
EXP is the inverse of LN, which is the natural logarithm of the given number.
To calculate powers of bases other than , use the exponentiation operator (^). For more
information, see Operator Reference.
Example
Description
The following formula calculates raised to the power of the number contained in the
column, [Power].
Code
=EXP([Power])
See Also
193
Scalar math and trig functions
LN Function
EXP
LOG10
LOG
FACT Function
Returns the factorial of a number, equal to the series 1*2*3*...* , ending in the given
number.
Syntax
FACT(<number>)
Parameters
Term Definition
Return Value
A decimal number.
Remarks
If the number is not an integer, it is truncated and an error is returned. If the result is too
large, an error is returned.
Example
Description
The following formula returns the factorial for the series of integers in the column,
[Values].
Code
=FACT([Values])
Comments
The following table shows the expected results:
194
Values Results
0 1
1 1
2 2
3 6
4 24
5 120
170 7.257415615308E+306
See Also
Scalar math and trig functions
TRUNC
FLOOR Function
Rounds a number down, toward zero, to the nearest multiple of significance.
Syntax
FLOOR(<number>, <significance>)
Parameters
Term Definition
Return Value
A decimal number.
Remarks
If either argument is nonnumeric, FLOOR returns #VALUE! error value.
If number and significance have different signs, FLOOR returns the #NUM! error value.
195
Regardless of the sign of the number, a value is rounded down when adjusted away from
zero. If the number is an exact multiple of significance, no rounding occurs.
Example
Description
The following formula takes the values in the [Total Product Cost] column from the table,
InternetSales.and rounds down to the nearest multiple of .1.
Code
=FLOOR(InternetSales[Total Product Cost],.5)
Comments
The following table shows the expected results for some sample values.
10.8423 10.8
8.0373 8
2.9733 2.9
See Also
Scalar math and trig functions
INT Function
Rounds a number down to the nearest integer.
Syntax
INT(<number>)
Parameters
Term Definition
Return Value
A whole number.
Remarks
196
TRUNC and INT are similar in that both return integers. TRUNC removes the fractional
part of the number. INT rounds numbers down to the nearest integer based on the value
of the fractional part of the number. INT and TRUNC are different only when using
negative numbers: TRUNC(-4.3) returns -4, but INT(-4.3) returns -5 because -5 is the
lower number.
Example
Description
The following expression rounds the value to 1. If you use the ROUND function, the
result would be 2.
Code
=INT(1.5)
See Also
math and trig functions
ROUND
ROUNDUP
ROUNDDOWN
MROUND
ISO.CEILING Function
Rounds a number up, to the nearest integer or to the nearest multiple of significance.
Syntax
ISO.CEILING(<number>[, <significance>])
Parameters
Term Definition
197
Return Value
A number, of the same type as the number argument, rounded as specified.
Remarks
There are two CEILING functions in DAX, with the following differences:
• The CEILING function emulates the behavior of the CEILING function in Excel.
• The ISO.CEILING function follows the ISO-defined behavior for determining the
ceiling value.
The two functions return the same value for positive numbers, but different values for
negative numbers. When using a positive multiple of significance, both CEILING and
ISO.CEILING round negative numbers upward (toward positive infinity). When using a
negative multiple of significance, CEILING rounds negative numbers downward (toward
negative infinity), while ISO.CEILING rounds negative numbers upward (toward positive
infinity).
The result type is usually the same type of the significance used as argument with the
following exceptions:
• If the first argument is of currency type then the result will be currency type.
• If the optional argument is not included the result is of integer type.
• If the significance argument is of Boolean type then the result is of integer type.
• If the significance argument is non-numeric type then the result is of real type.
Example: Positive Numbers
Description
The following formula returns 4.45. This might be useful if you want to avoid using
smaller units in your pricing. If an existing product is priced at $4.42, you can use
ISO.CEILING to round prices up to the nearest unit of five cents.
Code
=ISO.CEILING(4.42,0.05)
Example: Negative Numbers
Description
The following formula returns the ISO ceiling value of -4.40.
Code
=ISO.CEILING(-4.42,0.05)
See Also
Math and Trig functions
FLOOR function
CEILING Function (DAX)
ROUNDUP function
198
LN Function
Returns the natural logarithm of a number. Natural logarithms are based on the constant
(2.71828182845904).
Syntax
LN(<number>)
Parameters
Term Definition
Return Value
A decimal number.
Remarks
LN is the inverse of the EXP function.
Example
Description
The following example returns the natural logarithm of the number in the column,
[Values].
Code
=LN([Values])
See Also
Scalar math and trig functions
EXP Function
LOG Function
Returns the logarithm of a number to the base you specify.
Syntax
LOG(<number>,<base>)
Parameters
199