0% found this document useful (0 votes)
32 views254 pages

? Master DAX in Power BI With Real Example

Uploaded by

jmll89
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
32 views254 pages

? Master DAX in Power BI With Real Example

Uploaded by

jmll89
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 254

Contents

Data Analysis Expressions (DAX) Reference


Learn
DAX Overview
Videos
DAX functions
DAX function reference overview
New DAX functions
Date and time functions
Date and time functions overview
CALENDAR
CALENDARAUTO
DATE
DATEDIFF
DATEVALUE
DAY
EDATE
EOMONTH
HOUR
MINUTE
MONTH
NOW
SECOND
TIME
TIMEVALUE
TODAY
UTCNOW
UTCTODAY
WEEKDAY
WEEKNUM
YEAR
YEARFRAC
Time-intelligence functions
Time-intelligence functions overview
CLOSINGBALANCEMONTH
CLOSINGBALANCEQUARTER
CLOSINGBALANCEYEAR
DATEADD
DATESBETWEEN
DATESINPERIOD
DATESMTD
DATESQTD
DATESYTD
ENDOFMONTH
ENDOFQUARTER
ENDOFYEAR
FIRSTDATE
FIRSTNONBLANK
LASTDATE
LASTNONBLANK
NEXTDAY
NEXTMONTH
NEXTQUARTER
NEXTYEAR
OPENINGBALANCEMONTH
OPENINGBALANCEQUARTER
OPENINGBALANCEYEAR
PARALLELPERIOD
PREVIOUSDAY
PREVIOUSMONTH
PREVIOUSQUARTER
PREVIOUSYEAR
SAMEPERIODLASTYEAR
STARTOFMONTH
STARTOFQUARTER
STARTOFYEAR
TOTALMTD
TOTALQTD
TOTALYTD
Filter functions
Filter functions overview
ADDMISSINGITEMS
ALL
ALLEXCEPT
ALLNOBLANKROW
ALLSELECTED
CALCULATE
CALCULATETABLE
CROSSFILTER
DISTINCT (column)
DISTINCT (table)
EARLIER
EARLIEST
FILTER
FILTERS
HASONEFILTER
HASONEVALUE
ISCROSSFILTERED
ISFILTERED
KEEPFILTERS
RELATED
RELATEDTABLE
SELECTEDVALUE
SUBSTITUTEWITHINDEX
USERELATIONSHIP
VALUES
Information functions
Information functions overview
CONTAINS
CUSTOMDATA
IN Operator / CONTAINSROW function
ISBLANK
ISERROR
ISEVEN
ISINSCOPE
ISLOGICAL
ISNONTEXT
ISNUMBER
ISODD
ISONORAFTER
ISTEXT
LOOKUPVALUE
USERNAME
Logical functions
Logical functions overview
AND
False
IF
IFERROR
IN
NOT
OR
SWITCH
True
Math and trig functions
Math and trig functions overview
ABS
ACOS
ACOSH
ASIN
ASINH
ATAN
ATANH
CEILING
COMBIN
COMBINA
COS
COSH
CURRENCY
DEGREES
DIVIDE
EVEN
EXP
FACT
FLOOR
GCD
INT
ISO.CEILING
LCM
LN
LOG
LOG10
MOD
MROUND
ODD
PI
POWER
PRODUCT
PRODUCTX
QUOTIENT
RADIANS
RAND
RANDBETWEEN
ROUND
ROUNDDOWN
ROUNDUP
SIGN
SQRT
SUM
SUMX
TRUNC
Other functions
Other functions overview
DATATABLE
ERROR
EXCEPT
GENERATESERIES
GROUPBY
INTERSECT
ISEMPTY
NATURALINNERJOIN
NATURALLEFTOUTERJOIN
SUMMARIZECOLUMNS
Table Constructor
TREATAS
UNION
VAR
Parent and child functions
Parent and child functions overview
Understanding functions for Parent-Child Hierarchies
PATH
PATHCONTAINS
PATHITEM
PATHITEMREVERSE
PATHLENGTH
Statistical functions
Statistical functions overview
ADDCOLUMNS
APPROXIMATEDISTINCTCOUNT
AVERAGE
AVERAGEA
AVERAGEX
BETA.DIST
BETA.INV
CHISQ.INV
CHISQ.INV.RT
CONFIDENCE.NORM
CONFIDENCE.T
COUNT
COUNTA
COUNTAX
COUNTBLANK
COUNTROWS
COUNTX
CROSSJOIN
DISTINCTCOUNT
EXPON.DIST
GENERATE
GENERATEALL
GEOMEAN
GEOMEANX
MAX
MAXA
MAXX
MEDIAN
MEDIANX
MIN
MINA
MINX
NORM.DIST
NORM.INV
NORM.S.DIST
NORM.S.INV
PERCENTILE.EXC
PERCENTILE.INC
PERCENTILEX.EXC
PERCENTILEX.INC
PERMUT
POISSON.DIST
RANK.EQ
RANKX
ROW
SAMPLE
SELECTCOLUMNS
SIN
SINH
STDEV.S
STDEV.P
STDEVX.S
STDEVX.P
SQRTPI
SUMMARIZE
T.DIST
T.DIST.2T
T.DIST.RT
T.INV
T.INV.2T
TAN
TANH
TOPN
VAR.S
VAR.P
VARX.S
VARX.P
XIRR
XNPV
Text functions
Text functions overview
BLANK
CODE
COMBINEVALUES
CONCATENATE
CONCATENATEX
EXACT
FIND
FIXED
FORMAT
FORMAT function overview
Pre-Defined Numeric Formats for FORMAT
Custom Numeric Formats for FORMAT
Pre-defined date and time formats for FORMAT
Custom date and time formats for FORMAT
LEFT
LEN
LOWER
MID
REPLACE
REPT
RIGHT
SEARCH
SUBSTITUTE
TRIM
UNICHAR
UPPER
VALUE
DAX syntax
DAX operators
DAX queries
DAX parameter-naming
Data Analysis Expressions (DAX) is a library of functions and operators that can be combined to build formulas and expressions in
Power BI Desktop, Azure Analysis Services, SQL Server Analysis Services, and Power Pivot in Excel.

DAX functions
Get detailed information for any of the over 200 DAX functions.

Learn DAX videos


Learn quickly with introductory and advanced videos.

DAX overview
Get the big picture. This article describes the most essential concepts in DAX.

DAX syntax
Learn about syntax and expression requirements in DAX.

DAX operators
Learn how operators are used in DAX expressions that compare values, perform arithmetic calculations, or work with
strings.

DAX queries
Use query tools to create an evaluate statement that queries your data model.
DAX overview
12/18/2018 • 30 minutes to read

Data Analysis Expressions (DAX) is a formula expression language used in Analysis Services, Power BI Desktop,
and Power Pivot in Excel. DAX formulas include functions, operators, and values to perform advanced calculations
and queries on data in related tables and columns in tabular data models.
This article provides only a basic introduction to the most important concepts in DAX. It describes DAX as it
applies to all the products that use it. Some functionality may not apply to certain products or use cases. Refer to
your product's documentation describing it's particular implementation of DAX.

Calculations
DAX calculation formulas are used in measures, calculated columns, calculated tables, and row filters.
Measures
Measures are dynamic calculation formulas where the results change depending on context. Measures are used in
reporting that support combining and filtering model data by using multiple attributes such as a Power BI report
or Excel PivotTable or PivotChart. Measures are created by using the DAX formula bar in the model designer.
A formula in a measure can use standard aggregation functions automatically created by using the Autosum
feature, such as COUNT or SUM, or you can define your own formula by using the DAX formula bar. Named
measures can be passed as an argument to other measures.
When you define a formula for a measure in the formula bar, a Tooltip feature shows a preview of what the results
would be for the total in the current context, but otherwise the results are not immediately output anywhere. The
reason you cannot see the (filtered) results of the calculation immediately is because the result of a measure cannot
be determined without context. To evaluate a measure requires a reporting client application that can provide the
context needed to retrieve the data relevant to each cell and then evaluate the expression for each cell. That client
might be an Excel PivotTable or PivotChart, a Power BI report, or a table expression in a DAX query in SQL Server
Management Studio (SSMS ).
Regardless of the client, a separate query is run for each cell in the results. That is to say, each combination of row
and column headers in a PivotTable, or each selection of slicers and filters in a Power BI report, generates a
different subset of data over which the measure is calculated. For example, using this very simple measure
formula:

Total Sales:=SUM([Sales Amount])

When a user places the TotalSales measure in the Values window in a PivotTable, and then places the Product
Category column from a Product table into the Filters window, the sum of Sales Amount is calculated and
displayed for each product category.
Unlike calculated columns and row filters, the syntax for a measure includes the measure's name preceding the
formula. In the example just provided, the name Total Sales appears preceding the formula. After you've created a
measure, the name and its definition appear in the reporting client application Field List, and depending on
perspectives and roles is available to all users of the model.
To learn more, see:
Measures in Power BI Desktop
Measures in Analysis Services
Measures in Power Pivot
Calculated columns
A calculated column is a column that you add to an existing table (in the model designer) and then create a DAX
formula that defines the column's values. Because a calculated column is created in a table in the data model,
they're not supported in models that retrieve data exclusively from a relational data source using DirectQuery
mode.
When a calculated column contains a valid DAX formula, values are calculated for each row as soon as the formula
is entered. Values are then stored in the in-memory data model. For example, in a Date table, when the formula is
entered into the formula bar:

=[Calendar Year] & " Q" & [Calendar Quarter]

A value for each row in the table is calculated by taking values from the Calendar Year column (in the same Date
table), adding a space and the capital letter Q, and then adding the values from the Calendar Quarter column (in
the same Date table). The result for each row in the calculated column is calculated immediately and appears, for
example, as 2017 Q1. Column values are only recalculated if the table or any related table is processed (refresh) or
the model is unloaded from memory and then reloaded, like when closing and reopening a Power BI Desktop file.
To learn more, see:
Calculated columns in Power BI Desktop
Calculated columns in Analysis Services
Calculated Columns in Power Pivot.
Calculated tables
A calculated table is a computed object, based on either a DAX query or formula expression, derived from all or
part of other tables in the same model. Instead of querying and loading values into your new table's columns from
a data source, a DAX formula defines the table’s values.
Calculated tables can be helpful in a role-playing dimension. An example is the Date table, as OrderDate, ShipDate,
or DueDate, depending on the foreign key relationship. By creating a calculated table for ShipDate explicitly, you
get a standalone table that is available for queries, as fully operable as any other table. Calculated tables are also
useful when configuring a filtered rowset, or a subset or superset of columns from other existing tables. This allows
you to keep the original table intact while creating variations of that table to support specific scenarios.
Calculated tables support relationships with other tables. The columns in your calculated table have data types,
formatting, and can belong to a data category. Calculated tables can be named, and surfaced or hidden just like any
other table. Calculated tables are re-calculated if any of the tables it pulls data from are refreshed or updated.
To learn more, see:
Calculated tables in Power BI Desktop
Calculated tables in Analysis Services.
Row filters (Row-level security)
In row filters, also known as Row -level security, a DAX formula must evaluate to a Boolean TRUE/FALSE condition,
defining which rows can be returned by the results of a query by members of a particular role. For example, for
members of the Sales role, the Customers table with the following DAX formula:

=Customers[Country] = "USA"

Members of the Sales role will only be able to view data for customers in the USA, and aggregates, such as SUM
are returned only for customers in the USA. Row filters are not available in Power Pivot in Excel.
When defining a row filter by using DAX formula, you are creating an allowed row set. This does not deny access
to other rows; rather, they are simply not returned as part of the allowed row set. Other roles can allow access to
the rows excluded by the DAX formula. If a user is a member of another role, and that role's row filters allow access
to that particular row set, the user can view data for that row.
Row filters apply to the specified rows as well as related rows. When a table has multiple relationships, filters apply
security for the relationship that is active. Row filters will be intersected with other row filters defined for related
tables.
To learn more, see:
Row -level security (RLS ) with Power BI
Row filters in Analysis Services

Queries
DAX queries can be created and run in SQL Server Management Studio (SSMS ) and open-source tools like DAX
Studio (daxstudio.org). Unlike DAX calculation formulas, which can only be created in tabular data models, DAX
queries can also be run against Analysis Services Multidimensional models. DAX queries are often easier to write
and more efficient than Multidimensional Data Expressions (MDX) queries.
A DAX query is a statement, similar to a SELECT statement in T-SQL. The most basic type of DAX query is an
evaluate statement. For example,

EVALUATE
( FILTER ( 'DimProduct', [SafetyStockLevel] < 200 ) )
ORDER BY [EnglishProductName] ASC

Returns in Results a table listing only those products with a SafetyStockLevel less than 200, in ascending order by
EnglishProductName.
You can create measures as part of the query. Measures exist only for the duration of the query. To learn more, see
DAX queries.

Formulas
DAX formulas are essential for creating calculations in calculated columns and measures, and securing your data
by using row level filters. To create formulas for calculated columns and measures, you will use the formula bar
along the top of the model designer window or the DAX Editor. To create formulas for row filters, you will use the
Role Manager dialog box. Information in this section is meant to get you started with understanding the basics of
DAX formulas.
Formula basics
DAX formulas can be very simple or quite complex. The following table shows some examples of simple formulas
that could be used in a calculated column.

Formula Description

=TODAY() Inserts today's date in every row of a calculated column.

=3 Inserts the value 3 in every row of a calculated column.

=[Column1] + [Column2] Adds the values in the same row of [Column1] and [Column2]
and puts the results in the calculated column of the same row.
Whether the formula you create is simple or complex, you can use the following steps when building a formula:
1. Each formula must begin with an equal sign (=).
2. You can either type or select a function name, or type an expression.
3. Begin to type the first few letters of the function or name you want, and AutoComplete displays a list of
available functions, tables, and columns. Press TAB to add an item from the AutoComplete list to the
formula.
You can also click the Fx button to display a list of available functions. To select a function from the
dropdown list, use the arrow keys to highlight the item, and click OK to add the function to the formula.
4. Supply the arguments to the function by selecting them from a dropdown list of possible tables and
columns, or by typing in values.
5. Check for syntax errors: ensure that all parentheses are closed and columns, tables and values are
referenced correctly.
6. Press ENTER to accept the formula.

NOTE
In a calculated column, as soon as you enter the formula and the formula is validated, the column is populated with values. In
a measure, pressing ENTER saves the measure definition with the table. If a formula is invalid, an error will be displayed.

In this example, let's look at a formula in a measure named Days in Current Quarter:

Days in Current Quarter = COUNTROWS( DATESBETWEEN( 'Date'[Date], STARTOFQUARTER( LASTDATE('Date'[Date])),


ENDOFQUARTER('Date'[Date])))

This measure is used to create a comparison ratio between an incomplete period and the previous period. The
formula must take into account the proportion of the period that has elapsed, and compare it to the same
proportion in the previous period. In this case, [Days Current Quarter to Date]/[Days in Current Quarter] gives the
proportion elapsed in the current period.
This formula contains the following elements:

FORMULA ELEMENT DESCRIPTION

Days in Current Quarter The name of the measure.

= The equals sign (=) begins the formula.

COUNTROWS COUNTROWS counts the number of rows in the Date table

() Open and closing parenthesis specifies arguments.

DATESBETWEEN The DATESBETWEEN function returns the dates between the


last date for each value in the Date column in the Date table.

'Date' Specifies the Date table. Tables are in single quotes.

[Date] Specifies the Date column in the Date table. Columns are in
brackets.
FORMULA ELEMENT DESCRIPTION

STARTOFQUARTER The STARTOFQUARTER function returns the date of the start


of the quarter.

LASTDATE The LASTDATE function returns the last date of the quarter.

'Date' Specifies the Date table.

[Date] Specifies the Date column in the Date table.

ENDOFQUARTER The ENDOFQUARTER function

'Date' Specifies the Date table.

[Date] Specifies the Date column in the Date table.

Using formula AutoComplete


Both the formula bar in the model designer and the formula Row Filters window in the Role Manager dialog box
provide an AutoComplete feature. AutoComplete helps you enter a valid formula syntax by providing you with
options for each element in the formula.
You can use formula AutoComplete in the middle of an existing formula with nested functions. The text
immediately before the insertion point is used to display values in the drop-down list, and all of the text
after the insertion point remains unchanged.
AutoComplete does not add the closing parenthesis of functions or automatically match parentheses. You
must make sure that each function is syntactically correct or you cannot save or use the formula.
Using multiple functions in a formula
You can nest functions, meaning that you use the results from one function as an argument of another function.
You can nest up to 64 levels of functions in calculated columns. However, nesting can make it difficult to create or
troubleshoot formulas. Many functions are designed to be used solely as nested functions. These functions return a
table, which cannot be directly saved as a result; it must be provided as input to a table function. For example, the
functions SUMX, AVERAGEX, and MINX all require a table as the first argument.

Functions
DAX includes functions you can use to perform calculations using dates and times, create conditional values, work
with strings, perform lookups based on relationships, and the ability to iterate over a table to perform recursive
calculations. If you are familiar with Excel formulas, many of these functions will appear very similar; however, DAX
formulas are different in the following important ways:
A DAX function always references a complete column or a table. If you want to use only particular values
from a table or column, you can add filters to the formula.
If you need to customize calculations on a row -by-row basis, DAX provides functions that let you use the
current row value or a related value as a kind of parameter, to perform calculations that vary by context. To
understand how these functions work, see Context in this article.
DAX includes many functions that return a table, rather than a value. The table is not displayed in a
reporting client, but is used to provide input to other functions. For example, you can retrieve a table and
then count the distinct values in it, or calculate dynamic sums across filtered tables or columns.
DAX functions include a variety of time-intelligence functions. These functions let you define or select date
ranges, and perform dynamic calculations based on these dates or range. For example, you can compare
sums across parallel periods.
Date and time functions
The date and time functions in DAX are similar to date and time functions in Microsoft Excel. However, DAX
functions are based on the datetime data types used by Microsoft SQL Server. For more information, see Date
and time functions.
Filter functions
The filter functions in DAX return specific data types, look up values in related tales, and filter by related values. 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 more information, see Filter 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. For more information, see Information functions.
Logical functions
Logical functions act upon an expression to return information about the values in the expression. For example, the
TRUE function lets you know whether an expression that you are evaluating returns a TRUE value. For more
information, see Logical functions.
Mathematical and trigonometric functions
The mathematical functions in DAX are very similar to the Excel mathematical and trigonometric functions. Some
minor differences exist in the numeric data types used by DAX functions. For more information, see Math and trig
functions.
Other functions
These functions perform unique actions that cannot be defined by any of the categories most other functions
belong to. For more information, see Other functions.
Statistical functions
DAX provides statistical functions that perform aggregations. In addition to creating sums and averages, or finding
the minimum and maximum values, in DAX you can also filter a column before aggregating or create aggregations
based on related tables. For more information, see Statistical functions.
Text functions
The text functions in DAX are very similar to their counterparts in Excel. You can return part of a string, search for
text within a string, or concatenate string values. DAX also provides functions for controlling the formats for dates,
times, and numbers. For more information, see Text functions.
Time -intelligence functions
The time-intelligence functions provided in DAX let you create calculations that use built-in knowledge about
calendars and dates. By using time and date ranges in combination with aggregations or calculations, you can build
meaningful comparisons across comparable time periods for sales, inventory, and so on. For more information, see
Time-intelligence functions (DAX).
Table -valued functions
There are DAX functions that output tables, take tables as input, or do both. Because a table can have a single
column, table-valued functions also take single columns as inputs. Understanding how to use table-valued
functions is important for fully utilizing DAX formulas. DAX includes the following types of table-valued functions:
Filter functions return a column, table, or values related to the current row.
Aggregation functions aggregate any expression over the rows of a table.
Time-intelligence functions return a table of dates, or use a table of dates to calculate an aggregation.
Examples of table functions include: FILTER, ALL, VALUES, DISTINCT, RELATEDTABLE.

Variables
You can create variables within an expression by using the VAR. VAR is technically not a function, it's a keyword
you use to store the result of an expression as a named variable. That variable can then be passed as an argument
to other measure expressions. For example:

VAR
TotalQty = SUM ( Sales[Quantity] )

Return

IF (
TotalQuantity > 1000,
TotalQuantity * 0.95,
TotalQuantity * 1.25
)

In this example, TotalQty can then be passed as a named variable to other expressions. Variables can be of any
scalar data type, including tables. Using variables in your DAX formulas can be incredibly powerful.

Data types
You can import data into a model from many different data sources that might support different data types. When
you import data into a model, the data is converted to one of the tabular model data types. When the model data is
used in a calculation, the data is then converted to a DAX data type for the duration and output of the calculation.
When you create a DAX formula, the terms used in the formula will automatically determine the value data type
returned.
DAX supports the following data types:

DATA TYPE IN MODEL DATA TYPE IN DAX DESCRIPTION

Whole Number A 64 bit (eight-bytes) integer value 1, 2 Numbers that have no decimal places.
Integers can be positive or negative
numbers, but must be whole numbers
between -9,223,372,036,854,775,808 (-
2^63) and 9,223,372,036,854,775,807
(2^63-1).
DATA TYPE IN MODEL DATA TYPE IN DAX DESCRIPTION

Decimal Number A 64 bit (eight-bytes) real number 1, 2 Real numbers are numbers that can
have decimal places. Real numbers
cover a wide range of values:

Negative values from -1.79E +308


through -2.23E -308

Zero

Positive values from 2.23E -308


through 1.79E + 308

However, the number of significant


digits is limited to 17 decimal digits.

Boolean Boolean Either a True or False value.

Text String A Unicode character data string. Can be


strings, numbers or dates represented
in a text format.

Date Date/time Dates and times in an accepted date-


time representation.

Valid dates are all dates after March 1,


1900.

Currency Currency Currency data type allows values


between -922,337,203,685,477.5808 to
922,337,203,685,477.5807 with four
decimal digits of fixed precision.

N/A Blank A blank is a data type in DAX that


represents and replaces SQL nulls. You
can create a blank by using the BLANK
function, and test for blanks by using
the logical function, ISBLANK.

Tabular data models also include the Table data type as the input or output to many DAX functions. For example,
the FILTER function takes a table as input and outputs another table that contains only the rows that meet the filter
conditions. By combining table functions with aggregation functions, you can perform complex calculations over
dynamically defined data sets.
While data types are typically automatically set, it is important to understand data types and how they apply, in-
particular, to DAX formulas. Errors in formulas or unexpected results, for example, are often caused by using a
particular operator that cannot be used with a data type specified in an argument. For example, the formula,
= 1 & 2 , returns a string result of 12. The formula, = "1" + "2" , however, returns an integer result of 3.

Context
Context is an important concept to understand when creating DAX formulas. Context is what enables you to
perform dynamic analysis, as the results of a formula change to reflect the current row or cell selection and also
any related data. Understanding context and using context effectively are critical for building high-performing,
dynamic analyses, and for troubleshooting problems in formulas.
Formulas in tabular models can be evaluated in a different context, depending on other design elements:
Filters applied in a PivotTable or report
Filters defined within a formula
Relationships specified by using special functions within a formula
There are different types of context: row context, query context, and filter context.
Row context
Row context can be thought of as "the current row". If you create a formula in a calculated column, the row context
for that formula includes the values from all columns in the current row. If the table is related to another table, the
content also includes all the values from the other table that are related to the current row.
For example, suppose you create a calculated column, =[Freight] + [Tax] , that adds together values from two
columns, Freight and Tax, from the same table. This formula automatically gets only the values from the current
row in the specified columns.
Row context also follows any relationships that have been defined between tables, including relationships defined
within a calculated column by using DAX formulas, to determine which rows in related tables are associated with
the current row.
For example, the following formula uses the RELATED function to fetch a tax value from a related table, based on
the region that the order was shipped to. The tax value is determined by using the value for region in the current
table, looking up the region in the related table, and then getting the tax rate for that region from the related table.

= [Freight] + RELATED('Region'[TaxRate])

This formula gets the tax rate for the current region from the Region table and adds it to the value of the Freight
column. In DAX formulas, you do not need to know or specify the specific relationship that connects the tables.
Multiple row context
DAX includes functions that iterate calculations over a table. These functions can have multiple current rows, each
with its own row context. In essence, these functions let you create formulas that perform operations recursively
over an inner and outer loop.
For example, suppose your model contains a Products table and a Sales table. Users might want to go through
the entire sales table, which is full of transactions involving multiple products, and find the largest quantity ordered
for each product in any one transaction.
With DAX you can build a single formula that returns the correct value, and the results are automatically updated
any time a user adds data to the tables.

=MAXX(FILTER(Sales,[ProdKey]=EARLIER([ProdKey])),Sales[OrderQty])

For a detailed example of this formula, see EARLIER.


To summarize, the EARLIER function stores the row context from the operation that preceded the current
operation. At all times, the function stores in memory two sets of context: one set of context represents the current
row for the inner loop of the formula, and another set of context represents the current row for the outer loop of
the formula. DAX automatically feeds values between the two loops so that you can create complex aggregates.
Query context
Query context refers to the subset of data that is implicitly retrieved for a formula. When a user places a measure
or other value field into a PivotTable or into a report based on a tabular model, the engine examines the row and
column headers, Slicers, and report filters to determine the context. Then, the necessary queries are run against the
data source to get the correct subset of data, make the calculations defined by the formula, and then populate each
cell in the PivotTable or report. The set of data that is retrieved is the query context for each cell.
Because context changes depending on where you place the formula, the results of the formula can also change.
For example, suppose you create a formula that sums the values in the Profit column of the Sales table:
=SUM('Sales'[Profit]) . If you use this formula in a calculated column within the Sales table, the results for the
formula will be the same for the entire table, because the query context for the formula is always the entire data set
of the Sales table. Results will have profit for all regions, all products, all years, and so on.
However, users typically don't want to see the same result hundreds of times, but instead want to get the profit for
a particular year, a particular country, a particular product, or some combination of these, and then get a grand
total.
In a PivotTable, context can be changed by adding or removing column and row headers and by adding or
removing Slicers. Whenever users add column or row headings to the PivotTable, they change the query context in
which the measure is evaluated. Slicing and filtering operations also affect context. Therefore, the same formula,
used in a measure, is evaluated in a different query context for each cell.
Filter context
Filter context is the set of values allowed in each column, or in the values retrieved from a related table. Filters can
be applied to the column in the designer, or in the presentation layer (reports and PivotTables). Filters can also be
defined explicitly by filter expressions within the formula.
Filter context is added when you specify filter constraints on the set of values allowed in a column or table, by
using arguments to a formula. Filter context applies on top of other contexts, such as row context or query context.
In tabular models, there are many ways to create filter context. Within the context of clients that can consume the
model, such as Power BI reports, users can create filters on the fly by adding slicers or report filters on the row and
column headings. You can also specify filter expressions directly within the formula, to specify related values, to
filter tables that are used as inputs, or to dynamically get context for the values that are used in calculations. You
can also completely clear or selectively clear the filters on particular columns. This is very useful when creating
formulas that calculate grand totals.
For more information about how to create filters within formulas, see the FILTER Function (DAX).
For an example of how filters can be cleared to create grand totals, see the ALL Function (DAX).
For examples of how to selectively clear and apply filters within formulas, see ALLEXCEPT.
Determining context in formulas
When you create a DAX formula, the formula is first tested for valid syntax, and then tested to make sure the
names of the columns and tables included in the formula can be found in the current context. If any column or
table specified by the formula cannot be found, an error is returned.
Context during validation (and recalculation operations) is determined as described in the preceding sections, by
using the available tables in the model, any relationships between the tables, and any filters that have been applied.
For example, if you have just imported some data into a new table and it is not related to any other tables (and you
have not applied any filters), the current context is the entire set of columns in the table. If the table is linked by
relationships to other tables, the current context includes the related tables. If you add a column from the table to a
report that has Slicers and maybe some report filters, the context for the formula is the subset of data in each cell
of the report.
Context is a powerful concept that can also make it difficult to troubleshoot formulas. We recommend that you
begin with simple formulas and relationships to see how context works. The following section provides some
examples of how formulas use different types of context to dynamically return results.

Operators
The DAX language uses four different types of calculation operators in formulas:
Comparison operators to compare values and return a logical TRUE\FALSE value.
Arithmetic operators to perform arithmetic calculations that return numeric values.
Text concatenation operators to join two or more text strings.
Logical operators that combine two or more expressions to return a single result.
For detailed information about operators used in DAX formulas, see DAX operators.

Working with tables and columns


Tables in tabular data models look like Excel tables, but are different in the way they work with data and with
formulas:
Formulas work only with tables and columns, not with individual cells, range references, or arrays.
Formulas can use relationships to get values from related tables. The values that are retrieved are always
related to the current row value.
You cannot have irregular or "ragged" data like you can in an Excel worksheet. Each row in a table must contain
the same number of columns. However, you can have empty values in some columns. Excel data tables and
tabular model data tables are not interchangeable.
Because a data type is set for each column, each value in that column must be of the same type.
Referring to tables and columns in formulas
You can refer to any table and column by using its name. For example, the following formula illustrates how to
refer to columns from two tables by using the fully qualified name:

=SUM('New Sales'[Amount]) + SUM('Past Sales'[Amount])

When a formula is evaluated, the model designer first checks for general syntax, and then checks the names of
columns and tables that you provide against possible columns and tables in the current context. If the name is
ambiguous or if the column or table cannot be found, you will get an error on your formula (an #ERROR string
instead of a data value in cells where the error occurs). For more information about naming requirements for
tables, columns, and other objects, see Naming Requirements in DAX syntax.
Table relationships
By creating relationships between tables, you gain the ability to look up data in another table and use related
values to perform complex calculations. For example, you can use a calculated column to look up all the shipping
records related to the current reseller, and then sum the shipping costs for each. In many cases, however, a
relationship might not be necessary. You can use the LOOKUPVALUE function in a formula to return the value in
result_columnName for the row that meets criteria specified in the search_column and search_value parameters.
Many DAX functions require that a relationship exist between the tables, or among multiple tables, in order to
locate the columns that you have referenced and return results that make sense. Other functions will attempt to
identify the relationship; however, for best results you should always create a relationship where possible. Tabular
data models support multiple relationships among tables. To avoid confusion or incorrect results, only one
relationship at a time is designated as the active relationship, but you can change the active relationship as
necessary to traverse different connections in the data in calculations. USERELATIONSHIP function can be used to
specify one or more relationships to be used in a specific calculation.
It's important to observe these formula design rules when using relationships:
When tables are connected by a relationship, you must ensure the two columns used as keys have values
that match. Referential integrity is not enforced, therefore it is possible to have non-matching values in a key
column and still create a relationship. If this happens, you should be aware that blank values or non-
matching values might affect the results of formulas.
When you link tables in your model by using relationships, you enlarge the scope, or context, in which your
formulas are evaluated. Changes in context resulting from the addition of new tables, new relationships, or
from changes in the active relationship can cause your results to change in ways that you might not
anticipate. For more information, see Context in this article.

Process and refresh


Process and recalculation are two separate but related operations. You should thoroughly understand these
concepts when designing a model that contains complex formulas, large amounts of data, or data that is obtained
from external data sources.
Process (refresh) is updating the data in a model with new data from an external data source.
Recalculation is the process of updating the results of formulas to reflect any changes to the formulas themselves
and to reflect changes in the underlying data. Recalculation can affect performance in the following ways:
The values in a calculated column are computed and stored in the model. To update the values in the
calculated column, you must process the model using one of three processing commands – Process Full,
Process Data, or Process Recalc. The result of the formula must always be recalculated for the entire
column, whenever you change the formula.
The values calculated by measures are dynamically evaluated whenever a user adds the measure to a pivot
table or open a report; as the user modifies the context, values returned by the measure change. The results
of the measure always reflect the latest in the in-memory cache.
Processing and recalculation have no effect on row filter formulas unless the result of a recalculation returns a
different value, thus making the row queryable or not queryable by role members.

Troubleshooting
If you get an error when defining a formula, the formula might contain either a syntactic error, semantic error, or
calculation error.
Syntactic errors are the easiest to resolve. They typically involve a missing parenthesis or comma. .
The other type of error occurs when the syntax is correct, but the value or a column referenced does not make
sense in the context of the formula. Such semantic and calculation errors might be caused by any of the following
problems:
The formula refers to a non-existing column, table, or function.
The formula appears to be correct, but when the data engine fetches the data, it finds a type mismatch and
raises an error.
The formula passes an incorrect number or type of parameters to a function.
The formula refers to a different column that has an error, and therefore its values are invalid.
The formula refers to a column that has not been processed, meaning it has metadata but no actual data to use
for calculations.
In the first four cases, DAX flags the entire column that contains the invalid formula. In the last case, DAX grays out
the column to indicate that the column is in an unprocessed state.

Apps and tools


Power BI Desktop
Power BI Desktop is a free data modeling and reporting application. The model designer includes a DAX editor for
creating DAX calculation formulas.
Power Pivot in Excel

The Power Pivot in Excel models designer includes a DAX editor for creating DAX calculation formulas.
Visual Studio

SQL Server Data Tools (SSDT) is an essential tool for creating and deploying Analysis Services data models. The
model designer includes a DAX editor for creating DAX calculation formulas.
Analysis Services Projects extension (VSIX) includes the same functionality in SSDT to create Analysis Services
modeling projects. Do not install packages if SSDT is already installed.
SQL Server Management Studio

SQL Server Management Studio (SSMS ) is an essential tool for working with Analysis Services. SSMS includes a
DAX query editor for querying both tabular and multidimensional models.
DAX Studio

DAX Studio is an open-source client tool for creating and running DAX queries against Analysis Services, Power BI
Desktop, and Power Pivot in Excel models.

Learning resources
When learning DAX, it's best to use the application you'll be using to create your data models. Analysis Services,
Power BI Desktop, and Power Pivot in Excel all have articles and tutorials that include lessons on creating
measures, calculated columns, and row -filters by using DAX. Here are some additional resources:
Videos
DAX basics in Power BI Desktop
QuickStart: Learn DAX Basics in 30 Minutes (Power Pivot in Excel)
DAX Resource Center wiki
The Definitive Guide to DAX by Alberto Ferrari and Marco Russo (Microsoft Press). This extensive guide provides
basics to innovative high-performance techniques for beginning data modelers and BI professionals.
Videos
12/10/2018 • 2 minutes to read

Whether you're using Power BI Desktop, Power Pivot in Excel, or Analysis Services, learning Data Analysis
Expressions (DAX) is essential to creating effective data models. Here are some videos to help you get started
using this powerful expression language.

DAX 101
In this DAX 101 video, Microsoft Partner, Alberto Ferrari introduces essential concepts in DAX. With practical and
clear examples, you will learn about measures, calculated columns, and basic data modeling expressions with DAX.

Advanced DAX
In this advanced DAX video, Microsoft Partner, Alberto Ferrari describes DAX theory, filter and row context, and
other essential concepts in DAX.
DAX function reference
12/10/2018 • 2 minutes to read

This function reference provides detailed information including syntax, parameters, Return values, and examples
for each of the over 200 functions used in Data Analysis Expression (DAX) formulas.

IMPORTANT
Not all DAX functions are supported or included in earlier versions of Power BI Desktop, Analysis Services, and Power Pivot
in Excel.

In this section
New DAX functions - These functions are new or are existing functions that have been significantly updated.
Date and time functions (DAX) - These functions in DAX are similar to date and time functions in Microsoft Excel.
However, DAX functions are based on the datetime data types used by Microsoft SQL Server.
Time-intelligence functions (DAX) - These functions help you create calculations that use built-in knowledge
about calendars and dates. By using time and date ranges in combination with aggregations or calculations, you
can build meaningful comparisons across comparable time periods for sales, inventory, and so on.
Filter functions (DAX) - These functions help you return specific data types, look up values in related tables, and
filter by related values. Lookup functions work by using tables and relationships between them. Filtering functions
let you manipulate data context to create dynamic calculations.
Information functions (DAX) - These functions look at a table or column provided as an argument to another
function and tells you whether the value matches the expected type. For example, the ISERROR function returns
TRUE if the value you reference contains an error.
Logical functions (DAX) - These functions return information about values in an expression. For example, the
TRUE function lets you know whether an expression that you are evaluating returns a TRUE value.
Math and Trig functions (DAX) - Mathematical functions in DAX are similar to Excel's mathematical and
trigonometric functions. However, there are some differences in the numeric data types used by DAX functions.
Other functions (DAX) - These functions perform unique actions that cannot be defined by any of the categories
most other functions belong to.
Parent and Child functions (DAX) - These Data Analysis Expressions (DAX) functions help users manage data that
is presented as a parent/child hierarchy in their data models.
Statistical functions (DAX) - These functions perform aggregations. In addition to creating sums and averages, or
finding minimum and maximum values, in DAX you can also filter a column before aggregating or create
aggregations based on related tables.
Text functions (DAX) - With these functions, you can return part of a string, search for text within a string, or
concatenate string values. Additional functions are for controlling the formats for dates, times, and numbers.

See also
DAX Syntax Reference
DAX Operator Reference
DAX Parameter-Naming Conventions
New DAX functions
1/14/2019 • 2 minutes to read

DAX is continuously being improved with new functions and functionality to support new features. New functions
and updates are included in service, application, and tool updates which in most cases are monthly. SQL Server
Analysis Services and Excel are updated in the next cumulative update. To get the latest, make sure you're using the
latest version.

IMPORTANT
Not all functions are supported in all versions of Power BI Desktop, Analysis Services, and Power Pivot in Excel.

New functions
FUNCTION MONTH

APPROXIMATEDISTINCTCOUNT (Preview) Dec. 2018

ISINSCOPE Nov. 2018

NORM.DIST August 2018

NORM.INV August 2018

NORM.S.DIST August 2018

NORM.S.INV August 2018

T.DIST August 2018

T.DIST.2T August 2018

T.DIST.RT August 2018

T.INV August 2018

T.INV.2T August 2018

DISTINCT (table) April 2018

COMBINEVALUES March 2018

UTCNOW March 2018

UTCTODAY March 2018

Updated functions
FUNCTION MONTH

SUMMARIZECOLUMNS function Nov. 2018

NOTE
While functions and functionality are being updated all the time, only those updates that have a visible and functional change
exposed to users are described in documentation.
Date and time functions
12/10/2018 • 2 minutes to read

These functions help you create calculations based on dates and time. Many of the functions in DAX are
similar to the Excel date and time functions. However, DAX functions use a datetime data type, and can take
values from a column as an argument.

In this section
CALENDAR
CALENDARAUTO
DATE
DATEDIFF
DATEVALUE
DAY
EDATE
EOMONTH
HOUR
MINUTE
MONTH
NOW
SECOND
TIME
TIMEVALUE
TODAY
WEEKDAY
WEEKNUM
YEAR
YEARFRAC
CALENDAR
12/10/2018 • 2 minutes to read

Returns a table with a single column named “Date” that contains a contiguous set of dates. The range of dates is
from the specified start date to the specified end date, inclusive of those two dates.

Syntax
CALENDAR(<start_date>, <end_date>)

Parameters

TERM DEFINITION

start_date Any DAX expression that returns a datetime value.

end_date Any DAX expression that returns a datetime value.

Return value
Returns a table with a single column named “Date” containing a contiguous set of dates. The range of dates is from
the specified start date to the specified end date, inclusive of those two dates.

Remarks
An error is returned if start_date is greater than end_date.

Examples
The following formula returns a table with dates between January 1st, 2005 and December 31st, 2015.
=CALENDAR (DATE (2005, 1, 1), DATE (2015, 12, 31))

For a data model which includes actual sales data and future sales forecasts. The following expression returns the
date table covering the range of dates in these two tables.
=CALENDAR (MINX (Sales, [Date]), MAXX (Forecast, [Date]))
CALENDARAUTO
12/10/2018 • 2 minutes to read

Returns a table with a single column named “Date” that contains a contiguous set of dates. The range of dates is
calculated automatically based on data in the model.

Syntax
CALENDARAUTO([fiscal_year_end_month])

Parameters

TERM DEFINITION

fiscal_year_end_month Any DAX expression that returns an integer from 1 to 12. If


omitted, defaults to the value specified in the calendar table
template for the current user, if present; otherwise, defaults to
12.

Return value
Returns a table with a single column named “Date” that contains a contiguous set of dates. The range of dates is
calculated automatically based on data in the model.

Remarks
The date range is calculated as follows:
The earliest date in the model which is not in a calculated column or calculated table is taken as the
MinDate.
The latest date in the model which is not in a calculated column or calculated table is taken as the MaxDate.
The date range returned is dates between the beginning of the fiscal year associated with MinDate and the
end of the fiscal year associated with MaxDate.
An error is returned if the model does not contain any datetime values which are not in calculated columns or
calculated tables.

Example
In this example, the MinDate and MaxDate in the data model are July 1, 2010 and June 30, 2011.
CALENDARAUTO() will return all dates between January 1, 2010 and December 31, 2011.
CALENDARAUTO(3) will return all dates between March 1, 2010 and February 28, 2012.
DATE
12/10/2018 • 4 minutes to read

Returns the specified date in datetime format.

Syntax
DATE(<year>, <month>, <day>)

Parameters

TERM DEFINITION

year A number representing the year.

The value of the year argument can include one to four digits.
The year argument is interpreted according to the date
system used by your computer.

Dates beginning with March 1, 1900 are supported.

If you enter a number that has decimal places, the number is


rounded.

For values greater than 9999 or less than zero (negative


values), the function returns a #VALUE! error.

If the year value is between 0 and 1899, the value is added to


1900 to produce the final value. See the examples below.
Note: You should use four digits for the year argument
whenever possible to prevent unwanted results. For example,
using 07 returns 1907 as the year value.

month A number representing the month or a calculation according


to the following rules:

If month is a number from 1 to 12, then it represents a


month of the year. 1 represents January, 2 represents
February, and so on until 12 that represents December.

If you enter an integer larger than 12, the following


computation occurs: the date is calculated by adding the value
of month to the year. For example, if you have DATE( 2008,
18, 1), the function returns a datetime value equivalent to
June 1st of 2009, because 18 months are added to the
beginning of 2008 yielding a value of June 2009. See
examples below.

If you enter a negative integer, the following computation


occurs: the date is calculated subtracting the value of month
from year. For example, if you have DATE( 2008, -6, 15), the
function returns a datetime value equivalent to June 15th of
2007, because when 6 months are subtracted from the
beginning of 2008 it yields a value of June 2007. See
examples below.
TERM DEFINITION

day A number representing the day or a calculation according to


the following rules:

If day is a number from 1 to the last day of the given month


then it represents a day of the month.

If you enter an integer larger than last day of the given


month, the following computation occurs: the date is
calculated by adding the value of day to month. For example,
in the formula DATE( 2008, 3, 32) , the DATE function
returns a datetime value equivalent to April 1st of 2008,
because 32 days are added to the beginning of March
yielding a value of April 1st.

If you enter a negative integer, the following computation


occurs: the date is calculated subtracting the value of day
from month. For example, in the formula
DATE( 2008, 5, -15) , the DATE function returns a
datetime value equivalent to April 15th of 2008, because 15
days are subtracted from the beginning of May 2008 yielding
a value of April 2008.

If day contains a decimal portion, it is rounded to the nearest


integer value.

Return value
Returns the specified date (datetime).

Remarks
The DATE function takes the integers that are input as arguments, and generates the corresponding date. The
DATE function is most useful in situations where the year, month, and day are supplied by formulas. For example,
the underlying data might contain dates in a format that is not recognized as a date, such as YYYYMMDD. You can
use the DATE function in conjunction with other functions to convert the dates to a number that can be recognized
as a date.
In contrast to Microsoft Excel, which stores dates as a serial number, DAX date functions always return a datetime
data type. However, you can use formatting to display dates as serial numbers if you want.
This DAX function may return different results when used in a model that is deployed and then queried in
DirectQuery mode. For more information about semantic differences in DirectQuery mode, see
https://go.microsoft.com/fwlink/?LinkId=219171.

Example: Returning a Simple Date


Description
The following formula returns the date July 8, 2009:
Code

=DATE(2009,7,8)

Example: Years before 1899


Description
If the value that you enter for the year argument is between 0 (zero) and 1899 (inclusive), that value is added to
1900 to calculate the year. The following formula returns January 2, 1908: (1900+08).
Code

=DATE(08,1,2)

Example: Years before 1899


Description
If the value that you enter for the year argument is between 0 (zero) and 1899 (inclusive), that value is added to
1900 to calculate the year. The following formula returns January 2, 3700: (1900+1800).
Code

=DATE(1800,1,2)

Example: Years after 1899


Description
If year is between 1900 and 9999 (inclusive), that value is used as the year. The following formula returns January
2, 2008:
Code

=DATE(2008,1,2)

Example: Working with Months


Description
If month is greater than 12, month adds that number of months to the first month in the year specified. The
following formula returns the date February 2, 2009:
Code

=DATE(2008,14,2)

Comment
If the month value is less than 1, the DATE function subtracts the magnitude of that number of months, plus 1,
from the first month in the year specified. The following formula returns September 2, 2007:

=DATE(2008,-3,2)

Example: Working with Days


Description
If day is greater than the number of days in the month specified, day adds that number of days to the first day in
the month. The following formula returns the date February 4, 2008:
Code

=DATE(2008,1,35)

Comment
If day is less than 1, day subtracts the magnitude that number of days, plus one, from the first day of the month
specified. The following formula returns December 16, 2007:

=DATE(2008,1,-15)

See also
Date and time functions (DAX)
DAY function (DAX)
TODAY function (DAX)
DATEDIFF
12/10/2018 • 2 minutes to read

Returns the count of interval boundaries crossed between two dates.

Syntax
DATEDIFF(<start_date>, <end_date>, <interval>)

Parameters

TERM DEFINITION

start_date A scalar datetime value.

end_date A scalar datetime value Return value.

interval The interval to use when comparing dates. The value can be
one of the following:

- SECOND
- MINUTE
- HOUR
- DAY
- WEEK
- MONTH
- QUARTER
- YEAR

Return value
The count of interval boundaries crossed between two dates.

Remarks
An error is returned if start_date is larger than end_date.

Example
DATE

2012-12-31 23:59:59

2013-01-01 00:00:00

The following all return 1:


DATEDIFF(MIN( Calendar[Date] ), MAX( Calendar[Date], second ) )

DATEDIFF(MIN( Calendar[Date] ), MAX( Calendar[Date], minute ) )

DATEDIFF(MIN( Calendar[Date] ), MAX( Calendar[Date], hour ) )

DATEDIFF(MIN( Calendar[Date] ), MAX( Calendar[Date], day ) )

DATEDIFF(MIN( Calendar[Date] ), MAX( Calendar[Date], week ) )

DATEDIFF(MIN( Calendar[Date] ), MAX( Calendar[Date], month ) )

DATEDIFF(MIN( Calendar[Date] ), MAX( Calendar[Date], quarter ) )

DATEDIFF(MIN( Calendar[Date] ), MAX( Calendar[Date], year ) )


DATEVALUE
12/10/2018 • 2 minutes to read

Converts a date in the form of text to a date in datetime format.

Syntax
DATEVALUE(date_text)

Parameters

TERM DEFINITION

date_text Text that represents a date.

Property Value/Return value


A date in datetime format.

Remarks
The DATEVALUE function uses the locale and date/time settings of the client computer to understand the text
value when performing the conversion. If the current date/time settings represent dates in the format of
Month/Day/Year, then the string, "1/8/2009", would be converted to a datetime value equivalent to January 8th
of 2009. However, if the current date and time settings represent dates in the format of Day/Month/Year, the same
string would be converted as a datetime value equivalent to August 1st of 2009.
If the year portion of the date_text argument is omitted, the DATEVALUE function uses the current year from your
computer's built-in clock. Time information in the date_text argument is ignored.

Example
The following example returns a different datetime value depending on your computer's locale and settings for
how dates and times are presented.
In date/time settings where the day precedes the month, the example returns a datetime value
corresponding to January 8th of 2009.
In date/time settings where the month precedes the day, the example returns a datetime value
corresponding to August 1st of 2009.

=DATEVALUE("8/1/2009")

See also
Date and time functions (DAX)
DAY
12/10/2018 • 2 minutes to read

Returns the day of the month, a number from 1 to 31.

Syntax
DAY(<date>)

Parameters

TERM DEFINITION

date A date in datetime format, or a text representation of a date.

Return value
An integer number indicating the day of the month.

Remarks
The DAY function takes as an argument the date of the day you are trying to find. Dates can be provided to the
function by using another date function, by using an expression that returns a date, or by typing a date in a
datetime format. You can also type a date in one of the accepted string formats for dates.
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 is Hijri, 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 day 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, and the function returns 8. However, if the current date/time
settings represent dates in the format of Day/Month/Year, the same string would be interpreted as a datetime
value equivalent to August 1st of 2009, and the function returns 1.

Example: Getting the Day from a Date Column


Description
The following formula returns the day from the date in the column, [Birthdate].
Code

=DAY([Birthdate])

Example: Getting the Day from a String Date


Description
The following formulas return the day, 4, using dates that have been supplied as strings in an accepted text format.
Code

=DAY("3-4-1007")
=DAY("March 4 2007")

Example: Using a Day Value as a Condition


Description
The following expression returns the day that each sales order was placed, and flags the row as a promotional sale
item if the order was placed on the 10th of the month.
Code

=IF( DAY([SalesDate])=10,"promotion","")

See also
Date and time functions (DAX)
TODAY function (DAX)
DATE function (DAX)
EDATE
12/10/2018 • 2 minutes to read

Returns the date that is the indicated number of months before or after the start date. Use EDATE to calculate
maturity dates or due dates that fall on the same day of the month as the date of issue.

Syntax
EDATE(<start_date>, <months>)

Parameters

TERM DEFINITION

start_date A date in datetime or text format that represents the start


date.

months An integer that represents the number of months before or


after start_date.

Return value
A date (datetime).

Remarks
In contrast to Microsoft Excel, which stores dates as sequential serial numbers, DAX works with dates in a
datetime format. Dates stored in other formats are converted implicitly.
If start_date is not a valid date, EDATE returns an error. Make sure that the column reference or date that you
supply as the first argument is a date.
If months is not an integer, it is truncated.
When the date argument is a text representation of the date, the EDATE 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 a date in the format of Month/Day/Year, then the following string "1/8/2009" is interpreted
as a datetime value equivalent to January 8th of 2009. However, if the current date time settings represent a date
in the format of Day/Month/Year, the same string would be interpreted as a datetime value equivalent to August
1st of 2009.
If the requested date is past the last day of the corresponding month, then the last day of the month is returned.
For example, the following functions: EDATE ("2009-01-29", 1), EDATE ("2009-01-30", 1), EDATE ("2009-01-31", 1)
return February 28th of 2009; that corresponds to one month after the start date.
This DAX function may return different results when used in a model that is deployed and then queried in
DirectQuery mode. For more information about semantic differences in DirectQuery mode, see
https://go.microsoft.com/fwlink/?LinkId=219171.

Example
The following example returns the date three months after the order date, which is stored in the column
[TransactionDate].

=EDATE([TransactionDate],3)

See also
EOMONTH function (DAX)
Date and time functions (DAX)
EOMONTH
12/10/2018 • 2 minutes to read

Returns the date in datetime format of the last day of the month, before or after a specified number of months.
Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month.

Syntax
EOMONTH(<start_date>, <months>)

Parameters

TERM DEFINITION

start_date The start date in datetime format, or in an accepted text


representation of a date.

months A number representing the number of months before or after


the start_date. Note: If you enter a number that is not an
integer, the number is rounded up or down to the nearest
integer.

Return value
A date (datetime).

Remarks
In contrast to Microsoft Excel, which stores dates as sequential serial numbers, DAX works with dates in a
datetime format. The EOMONTH function can accept dates in other formats, with the following restrictions:
If start_date is not a valid date, EOMONTH returns an error.
If start_date is a numeric value that is not in a datetime format, EOMONTH will convert the number to a date. To
avoid unexpected results, convert the number to a datetime format before using the EOMONTH function.
If start_date plus months yields an invalid date, EOMONTH returns an error. Dates before March 1st of 1900 and
after December 31st of 9999 are invalid.
When the date argument is a text representation of the date, the EDATE function uses the locale and date time
settings, of the client computer, to understand the text value in order to perform the conversion. If current date
time settings represent a date in the format of Month/Day/Year, then the following string "1/8/2009" is interpreted
as a datetime value equivalent to January 8th of 2009. However, if the current date time settings represent a date
in the format of Day/Month/Year, the same string would be interpreted as a datetime value equivalent to August
1st of 2009.
This DAX function may return different results when used in a model that is deployed and then queried in
DirectQuery mode. For more information about semantic differences in DirectQuery mode, see
https://go.microsoft.com/fwlink/?LinkId=219171.

Example
The following expression returns May 31, 2008, because the months argument is rounded to 2.

=EOMONTH("March 3, 2008",1.5)

See also
EDATE function (DAX)
Date and time functions (DAX)
HOUR
12/10/2018 • 2 minutes to read

Returns the hour as a number from 0 (12:00 A.M.) to 23 (11:00 P.M.).

Syntax
HOUR(<datetime>)

Parameters

TERM DEFINITION

datetime A datetime value, such as 16:48:00 or 4:48 PM.

Return value
An integer number from 0 to 23.

Remarks
The HOUR function takes as argument the time that contains the hour you want to find. You can supply the time
by using a date/time function, an expression that returns a datetime, or by typing the value directly in one of the
accepted time formats. Times can also be entered as any accepted text representation of a time.
When the datetime argument is a text representation of the date and time, the function uses the locale and
date/time settings of the client computer to understand the text value in order to perform the conversion. Most
locales use the colon (:) as the time separator and any input text using colons as time separators will parse
correctly. Review your locale settings to understand your results.

Example
The following example returns the hour from the TransactionTime column of a table named Orders.

=HOUR('Orders'[TransactionTime])

Example
The following example returns 15, meaning the hour corresponding to 3 PM in a 24-hour clock. The text value is
automatically parsed and converted to a date/time value.

=HOUR("March 3, 2008 3:00 PM")

See also
Date and time functions (DAX)
MINUTE function (DAX)
YEAR function (DAX)
SECOND function (DAX)
MINUTE
12/10/2018 • 2 minutes to read

Returns the minute as a number from 0 to 59, given a date and time value.

Syntax
MINUTE(<datetime>)

Parameters

TERM DEFINITION

datetime A datetime value or text in an accepted time format, such as


16:48:00 or 4:48 PM.

Return value
An integer number from 0 to 59.

Remarks
In contrast to Microsoft Excel, which stores dates and times in a serial numeric format, DAX uses a datetime data
type for dates and times. You can provide the datetime value to the MINUTE function by referencing a column
that stores dates and times, by using a date/time function, or by using an expression that returns a date and time.
When the datetime argument is a text representation of the date and time, the function uses the locale and
date/time settings of the client computer to understand the text value in order to perform the conversion. Most
locales use the colon (:) as the time separator and any input text using colons as time separators will parse
correctly. Verify your locale settings to understand your results.

Example
The following example returns the minute from the value stored in the TransactionTime column of the Orders
table.

=MINUTE(Orders[TransactionTime])

Example
The following example returns 45, which is the number of minutes in the time 1:45 PM.

=MINUTE("March 23, 2008 1:45 PM")

See also
Date and time functions (DAX)
HOUR function (DAX)
YEAR function (DAX)
SECOND function (DAX)
MONTH
12/10/2018 • 2 minutes to read

Returns the month as a number from 1 (January) to 12 (December).

Syntax
MONTH(<datetime>)

Parameters

TERM DEFINITION

date A date in datetime or text format.

Return value
An integer number from 1 to 12.

Remarks
In contrast to Microsoft Excel, which stores dates as serial numbers, DAX uses a datetime format when working
with dates. You can enter the date used as argument to the MONTH function by typing an accepted datetime
format, by providing a reference to a column that contains dates, or by using an expression that returns a date.
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 is Hijri, 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. If the current date time
settings represent a date in the format of Month/Day/Year, then the following string "1/8/2009" is interpreted as a
datetime value equivalent to January 8th of 2009, and the function yields a result of 1. However, if the current date
time settings represent a date in the format of Day/Month/Year, then the same string would be interpreted as a
datetime value equivalent to August 1st of 2009, and the function yields a result of 8.
If the text representation of the date cannot be correctly converted to a datetime value, the function returns an
error.

Example
The following expression returns 3, which is the integer corresponding to March, the month in the date argument.

=MONTH("March 3, 2008 3:45 PM")

Example
The following expression returns the month from the date in the TransactionDate column of the Orders table.
=MONTH(Orders[TransactionDate])

See also
Date and time functions (DAX)
HOUR function (DAX)
MINUTE function (DAX)
YEAR function (DAX)
SECOND function (DAX)
NOW
12/10/2018 • 2 minutes to read

Returns the current date and time in datetime format.


The NOW function is useful when you need to display the current date and time on a worksheet or calculate a
value based on the current date and time, and have that value updated each time you open the worksheet.

Syntax
NOW()

Return value
A date (datetime).

Remarks
The result of the NOW function changes only when the column that contains the formula is refreshed. It is not
updated continuously.
The TODAY function returns the same date but is not precise with regard to time; the time returned is always
12:00:00 AM and only the date is updated.

Example
The following example returns the current date and time plus 3.5 days:

=NOW()+3.5

See also
UTCNOW function
TODAY function (DAX)
SECOND
12/10/2018 • 2 minutes to read

Returns the seconds of a time value, as a number from 0 to 59.

Syntax
SECOND(<time>)

Parameters

TERM DEFINITION

time A time in datetime format, such as 16:48:23 or 4:48:47 PM.

Return value
An integer number from 0 to 59.

Remarks
In contrast to Microsoft Excel, which stores dates and times as serial numbers, DAX uses a datetime format when
working with dates and times. If the source data is not in this format, DAX implicitly converts the data. You can use
formatting to display the dates and times as a serial number of you need to.
The date/time value that you supply as an argument to the SECOND function can be entered as a text string
within quotation marks (for example, "6:45 PM"). You can also provide a time value as the result of another
expression, or as a reference to a column that contains times.
If you provide a numeric value of another data type, such as 13.60, the value is interpreted as a serial number and
is represented as a datetime data type before extracting the value for seconds. To make it easier to understand
your results, you might want to represent such numbers as dates before using them in the SECOND function. For
example, if you use SECOND with a column that contains a numeric value such as, 25.56, the formula returns 24.
That is because, when formatted as a date, the value 25.56 is equivalent to January 25, 1900, 1:26:24 PM.
When the time argument is a text representation of a date and time, the function uses the locale and date/time
settings of the client computer to understand the text value in order to perform the conversion. Most locales use
the colon (:) as the time separator and any input text using colons as time separators will parse correctly. Review
your locale settings to understand your results.

Example
The following formula returns the number of seconds in the time contained in the TransactionTime column of a
table named Orders.

=SECOND('Orders'[TransactionTime])

Example
The following formula returns 3, which is the number of seconds in the time represented by the value, March 3,
2008 12:00:03.

=SECOND("March 3, 2008 12:00:03")

See also
Date and time functions (DAX)
HOUR function (DAX)
MINUTE function (DAX)
YEAR function (DAX)
TIME
12/10/2018 • 2 minutes to read

Converts hours, minutes, and seconds given as numbers to a time in datetime format.

Syntax
TIME(hour, minute, second)

Parameters

TERM DEFINITION

hour A number from 0 to 23 representing the hour.

Any value greater than 23 will be divided by 24 and the


remainder will be treated as the hour value.

minute A number from 0 to 59 representing the minute.

Any value greater than 59 will be converted to hours and


minutes.

second A number from 0 to 59 representing the second.

Any value greater than 59 will be converted to hours,


minutes, and seconds.

Return value
A time (datetime).

Remarks
In contrast to Microsoft Excel, which stores dates and times as serial numbers, DAX works with date and time
values in a datetime format. Numbers in other formats are implicitly converted when you use a date/time value in
a DAX function. If you need to use serial numbers, you can use formatting to change the way that the numbers are
displayed.
Time values are a portion of a date value, and in the serial number system are represented by a decimal number.
Therefore, the datetime value 12:00 PM is equivalent to 0.5, because it is half of a day.
You can supply the arguments to the TIME function as values that you type directly, as the result of another
expression, or by a reference to a column that contains a numeric value. The following restrictions apply:
Any value for hours that is greater than 23 will be divided by 24 and the remainder will be treated as the
hour value.
Any value for minutes that is greater than 59 will be converted to hours and minutes.
Any value for seconds that is greater than 59 will be converted to hours, minutes, and seconds.
For minutes or seconds, a value greater than 24 hours will be divided by 24 and the reminder will be treated
as the hour value. A value in excess of 24 hours does not alter the date portion.
To improve readability of the time values returned by this function, we recommend that you format the column or
PivotTable cell that contains the results of the formula by using one of the time formats provided by Microsoft
Excel.
This DAX function may return different results when used in a model that is deployed and then queried in
DirectQuery mode. For more information about semantic differences in DirectQuery mode, see
https://go.microsoft.com/fwlink/?LinkId=219171.

Example
The following examples both return the time, 3:00 AM:

=TIME(27,0,0)
=TIME(3,0,0)

Example
The following examples both return the time, 12:30 PM:

=TIME(0,750,0)
=TIME(12,30,0)

Example
The following example creates a time based on the values in the columns, intHours , intMinutes , intSeconds :

=TIME([intHours],[intMinutes],[intSeconds])

See also
DATE function (DAX)
Date and time functions (DAX)
TIMEVALUE function
12/10/2018 • 2 minutes to read

Converts a time in text format to a time in datetime format.

Syntax
TIMEVALUE(time_text)

Parameters

Term Definition

time_text A text string that that represents a certain time of the day.
Any date information included in the time_text argument is
ignored.

Return value
A date (datetime).

Remarks
Time values are a portion of a date value and represented by a decimal number. For example, 12:00 PM is
represented as 0.5 because it is half of a day.
When the time_text argument is a text representation of the date and time, the function uses the locale and
date/time settings of the client computer to understand the text value in order to perform the conversion. Most
locales use the colon (:) as the time separator, and any input text using colons as time separators will parse
correctly. Review your locale settings to understand your results.

Example
=TIMEVALUE("20:45:30")

See also
Date and time functions (DAX)
TODAY
12/10/2018 • 2 minutes to read

Returns the current date.

Syntax
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..

The NOW function is similar but returns the exact time, whereas TODAY returns the time value 12:00:00 PM for
all dates.

Example
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:

=YEAR(TODAY())-1963

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 (DAX)
NOW function (DAX)
UTCNOW
12/10/2018 • 2 minutes to read

Returns the current UTC date and time

Syntax
UTCNOW()

Return value
A (datetime).

Remarks
The result of the UTCNOW function changes only when the formula is refreshed. It is not continuously updated.

Example
The following:

EVALUATE { FORMAT(UTCNOW(), "General Date") }

Returns:

[VALUE]

2/2/2018 4:48:08 AM

See also
NOW function (DAX)
UTCTODAY function (DAX)
UTCTODAY
12/10/2018 • 2 minutes to read

Returns the current UTC date.

Syntax
UTCTODAY()

Return value
A date.

Remarks
UTCTODAY returns the time value 12:00:00 PM for all dates.
The UTCNOW function is similar but returns the exact time and date.

Example
The following:

EVALUATE { FORMAT(UTCTODAY(), "General Date") }

Returns:

[VALUE]

2/2/2018

See also
NOW function (DAX)
UTCNOW function (DAX)
WEEKDAY
12/10/2018 • 2 minutes to read

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>)

Parameters

TERM DEFINITION

date A date in datetime format.

Dates should be entered by using the DATE function, by using


expressions that result in a date, or as the result of other
formulas.

return_type A number that determines the Return value:

Return type: 1, week begins on Sunday (1) and ends on


Saturday (7). numbered 1 through 7.

Return type: 2, week begins on Monday (1) and ends on


Sunday (7).

Return type: 3, week begins on Monday (0) and ends on


Sunday (6).numbered 1 through 7.

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 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
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.

=WEEKDAY([HireDate]+1)

See also
Date and time functions (DAX)
WEEKNUM function (DAX)
YEARFRAC function (DAX)
WEEKNUM
12/10/2018 • 2 minutes to read

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

date The date in datetime format.

return_type A number that determines the Return value: use 1 when the
week begins on Sunday; use 2 when the week begins on
Monday. The default is 1.

Return type: 1, week begins on Sunday. Weekdays are


numbered 1 through 7.

Return type: 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
The following example returns the week number of the date February 14, 2010.

=WEEKNUM("Feb 14, 2010", 2)

Example
The following example returns the week number of the date stored in the column, HireDate, from the table,
Employees.

=WEEKNUM('Employees'[HireDate])

See also
Date and time functions (DAX)
YEARFRAC function (DAX)
WEEKDAY function (DAX)
YEAR
12/10/2018 • 2 minutes to read

Returns the year of a date as a four digit integer in the range 1900-9999.

Syntax
YEAR(<date>)

Parameters

TERM DEFINITION

date A date in datetime or text format, containing the year you


want to find.

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
The following example returns 2007.

=YEAR("March 2007")

Example: Date as Result of Expression


Description
The following example returns the year for today's date.
Code

=YEAR(TODAY())

See also
Date and time functions (DAX)
HOUR function (DAX)
MINUTE function (DAX)
YEAR function (DAX)
SECOND function (DAX)
YEARFRAC
12/10/2018 • 2 minutes to read

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
YEARFRAC(<start_date>, <end_date>, <basis>)

Parameters

TERM DEFINITION

start_date The start date in datetime format.

end_date The end date in datetime format.

basis (Optional) The type of day count basis to use. All arguments
are truncated to integers.

Basis - Description

0 - US (NASD) 30/360

1 - Actual/actual

2 - Actual/360

3 - Actual/365

4 - European 30/360

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
The following example returns the fraction of a year represented by the difference between the dates in the two
columns, TransactionDate and ShippingDate :
=YEARFRAC(Orders[TransactionDate],Orders[ShippingDate])

Example
The following example returns the fraction of a year represented by the difference between the dates, January 1
and March 1:

=YEARFRAC("Jan 1 2007","Mar 1 2007")

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 (DAX)
WEEKNUM function (DAX)
YEARFRAC function (DAX)
WEEKDAY function (DAX)
Time-intelligence functions
12/10/2018 • 2 minutes to read

Data Analysis Expressions (DAX) includes time intelligence functions to support the needs of Business
Intelligence analysis by enabling you to manipulate data using time periods, including days, months, quarters,
and years, and then build and compare calculations over those periods.

In this section
CLOSINGBALANCEMONTH
CLOSINGBALANCEQUARTER
CLOSINGBALANCEYEAR
DATEADD
DATESBETWEEN
DATESINPERIOD
DATESMTD
DATESQTD
DATESYTD
ENDOFMONTH
ENDOFQUARTER
ENDOFYEAR
FIRSTDATE
FIRSTNONBLANK
LASTDATE
LASTNONBLANK
NEXTDAY
NEXTMONTH
NEXTQUARTER
NEXTYEAR
OPENINGBALANCEMONTH
OPENINGBALANCEQUARTER
OPENINGBALANCEYEAR
PARALLELPERIOD
PREVIOUSDAY
PREVIOUSMONTH
PREVIOUSQUARTER
PREVIOUSYEAR
SAMEPERIODLASTYEAR
STARTOFMONTH
STARTOFQUARTER
STARTOFYEAR
TOTALMTD
TOTALQTD
TOTALYTD
CLOSINGBALANCEMONTH
12/10/2018 • 2 minutes to read

Evaluates the expression at the last date of the month in the current context.

Syntax
CLOSINGBALANCEMONTH(<expression>,<dates>[,<filter>])

Parameters

PARAMETER DEFINITION

expression An expression that returns a scalar value.

dates A column that contains dates.

filter (optional) An expression that specifies a filter to apply to the


current context.

Return value
A scalar value that represents the expression evaluated at the last date of the month in the current context.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

NOTE
The filter expression has restrictions described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'Month End Inventory Value' of the product
inventory.
To see how this works, create a PivotTable and add the fields, CalendarYear, MonthNumberOfYear and
DayNumberOfMonth, to the Row Labels area of the PivotTable. Then add a measure, named Month End
Inventory Value, using the formula defined in the code section, to the Values area of the PivotTable.

Code
=CLOSINGBALANCEMONTH(SUMX(ProductInventory,ProductInventory[UnitCost]*ProductInventory[UnitsBalance]),DateTime
[DateKey])

See also
Time-intelligence functions (DAX)
CLOSINGBALANCEYEAR function (DAX)
CLOSINGBALANCEQUARTER function (DAX)
Get Sample Data
CLOSINGBALANCEQUARTER
12/10/2018 • 2 minutes to read

Evaluates the expression at the last date of the quarter in the current context.

Syntax
CLOSINGBALANCEQUARTER(<expression>,<dates>[,<filter>])

Parameters

Parameter Definition

expression An expression that returns a scalar value.

dates A column that contains dates.

filter (optional) An expression that specifies a filter to apply to the


current context.

Return value
A scalar value that represents the expression evaluated at the last date of the quarter in the current context.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

NOTE
The filter expression has restrictions described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'Quarter End Inventory Value' of the product
inventory.
To see how this works, create a PivotTable and add the fields, CalendarYear, CalendarQuarter and
MonthNumberOfYear, to the Row Labels area of the PivotTable. Then add a measure, named Quarter End
Inventory Value, using the formula defined in the code section, to the Values area of the PivotTable.

Code
=CLOSINGBALANCEQUARTER(SUMX(ProductInventory,ProductInventory[UnitCost]*ProductInventory[UnitsBalance]),DateTi
me[DateKey])

See also
Time-intelligence functions (DAX)
CLOSINGBALANCEYEAR function (DAX)
CLOSINGBALANCEMONTH function (DAX)
Get Sample Data
CLOSINGBALANCEYEAR
12/10/2018 • 2 minutes to read

Evaluates the expression at the last date of the year in the current context.

Syntax
CLOSINGBALANCEYEAR(<expression>,<dates>[,<filter>][,<year_end_date>])

Parameters

Parameter Definition

expression An expression that returns a scalar value.

dates A column that contains dates.

filter (optional) An expression that specifies a filter to apply to the


current context.

year_end_date (optional) A literal string with a date that defines the year-end
date. The default is December 31.

Return value
A scalar value that represents the expression evaluated at the last date of the year in the current context.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

NOTE
The filter expression has the restrictions described in the topic, CALCULATE function (DAX).

The year_end_date parameter is a string literal of a date, in the same locale as the locale of the client where the
workbook was created. The year portion of the date is ignored.
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'Year End Inventory Value' of the product
inventory.
To see how this works, create a PivotTable and add the field, CalendarYear, to the Row Labels area of the
PivotTable. Then add a measure, named Year End Inventory Value, using the formula defined in the code
section, to the Values area of the PivotTable.

Code
=CLOSINGBALANCEYEAR(SUMX(ProductInventory,ProductInventory[UnitCost]*ProductInventory[UnitsBalance]),DateTime[
DateKey])

See also
Time-intelligence functions (DAX)
CLOSINGBALANCEYEAR function (DAX)
CLOSINGBALANCEQUARTER function (DAX)
CLOSINGBALANCEMONTH function (DAX)
Get Sample Data
DATEADD
12/10/2018 • 2 minutes to read

Returns a table that contains a column of dates, shifted either forward or backward in time by the specified
number of intervals from the dates in the current context.

Syntax
DATEADD(<dates>,<number_of_intervals>,<interval>)

Parameters

Term Definition

dates A column that contains dates.

number_of_intervals An integer that specifies the number of intervals to add to or


subtract from the dates.

interval The interval by which to shift the dates. The value for interval
can be one of the following: year , quarter , month , day

Return value
A table containing a single column of date values.

Remarks
The dates argument can be any of the following:
A reference to a date/time column,
A table expression that returns a single column of date/time values,
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

If the number specified for number_of_intervals is positive, the dates in dates are moved forward in time; if the
number is negative, the dates in dates are shifted back in time.
The interval parameter is an enumeration, not a set of strings; therefore values should not be enclosed in
quotation marks. Also, the values: year , quarter , month , day should be spelled in full when using them.
The result table includes only dates that exist in the dates column.
If the dates in the current context do not form a contiguous interval, 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 https://go.microsoft.com/fwlink/?LinkId=219172.

Example: Shifting a Set of Dates


Description
The following formula calculates dates that are one year before the dates in the current context.
Code

=DATEADD(DateTime[DateKey],-1,year)

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
Get Sample Data
DATESBETWEEN
12/10/2018 • 2 minutes to read

Returns a table that contains a column of dates that begins with the start_date and continues until the end_date.

Syntax
DATESBETWEEN(<dates>,<start_date>,<end_date>)

Parameters

Term Definition

dates A reference to a date/time column.

start_date A date expression.

end_date A date expression.

Return value
A table containing a single column of date values.

Remarks
If start_date is a blank date value, then start_date will be the earliest value in the dates column.
If end_date is a blank date value, then end_date will be the latest value in the dates column.
The dates used as the start_date and end_date are inclusive: that is, if the sales occurred on September 1 and you
use September 1 as the start date, sales on September 1 are counted.

NOTE
The DATESBETWEEN function is provided for working with custom date ranges. If you are working with common date
intervals such as months, quarters, and years, we recommend that you use the appropriate function, such as
DATESINPERIOD.

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'Summer 2007 sales' for the Internet sales.
To see how this works, create a PivotTable and add the field, CalendarYear, to the Row Labels area of the
PivotTable. Then add a measure, named Summer 2007 Sales, using the formula as defined in the code section, to
the Values area of the PivotTable.
=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]), DATESBETWEEN(DateTime[DateKey],
DATE(2007,6,1),
DATE(2007,8,31)
))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
DATESINPERIOD function (DAX)
DATESINPERIOD
12/10/2018 • 2 minutes to read

Returns a table that contains a column of dates that begins with the start_date and continues for the specified
number_of_intervals.

Syntax
DATESINPERIOD(<dates>,<start_date>,<number_of_intervals>,<interval>)

Parameters

Term Definition

dates A column that contains dates.

start_date A date expression.

number_of_intervals An integer that specifies the number of intervals to add to or


subtract from the dates.

interval The interval by which to shift the dates. The value for interval
can be one of the following: year , quarter , month , day

Return value
A table containing a single column of date values.

Remarks
The dates argument can be a reference to a date/time column.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

If the number specified for number_of_intervals is positive, the dates are moved forward in time; if the number
is negative, the dates are shifted back in time.
The interval parameter is an enumeration, not a set of strings; therefore values should not be enclosed in
quotation marks. Also, the values: year , quarter , month , day should be spelled in full when using them.
The result table includes only dates that appear in the values of the underlying table column.
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following formula returns the Internet sales for the 21 days prior to August 24, 2007.

= CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]),DATESINPERIOD(DateTime[DateKey],DATE(2007,08,24),-21,day))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
DATESBETWEEN function (DAX)
Get Sample Data
DATESMTD
12/10/2018 • 2 minutes to read

Returns a table that contains a column of the dates for the month to date, in the current context.

Syntax
DATESMTD(<dates>)

Parameters

Term Definition

dates A column that contains dates.

Property Value/Return value


A table containing a single column of date values.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'Month To Date Total' for the Internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear, MonthNumberOfYear and
DayNumberOfMonth, to the Row Labels area of the PivotTable. Then add a measure, named Month To Date
Total, using the formula defined in the code section, to the Values area of the PivotTable.

=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]), DATESMTD(DateTime[DateKey]))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
DATESYTD function (DAX)
DATESQTD function (DAX)
Get Sample Data
DATESQTD
12/10/2018 • 2 minutes to read

Returns a table that contains a column of the dates for the quarter to date, in the current context.

Syntax
DATESQTD(<dates>)

Parameters

Term Definition

dates A column that contains dates.

Property Value/Return value


A table containing a single column of date values.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'Quarterly Running Total' of the internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear, CalendarQuarter and
MonthNumberOfYear to the Row Labels area of the PivotTable. Then add a measure, named Quarterly Running
Total, using the formula defined in the code section, to the Values area of the PivotTable.

=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]), DATESQTD(DateTime[DateKey]))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
DATESYTD function (DAX)
DATESMTD function (DAX)
Get Sample Data
DATESYTD
12/10/2018 • 2 minutes to read

Returns a table that contains a column of the dates for the year to date, in the current context.

Syntax
DATESYTD(<dates> [,<year_end_date>])

Parameters

Term Definition

dates A column that contains dates.

year_end_date (optional) A literal string with a date that defines the year-end
date. The default is December 31.

Property Value/Return value


A table containing a single column of date values.

Remarks
The dates argument can be any of the following:
A reference to a date/time column,
A table expression that returns a single column of date/time values,
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

The year_end_date parameter is a string literal of a date, in the same locale as the locale of the client where the
workbook was created. The year portion of the date is ignored.
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'Running Total' for the Internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear and CalendarQuarter, to the Row
Labels area of the PivotTable. Then add a measure named Running Total, using the formula defined in the code
section, to the Values area of the PivotTable.
=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]), DATESYTD(DateTime[DateKey]))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
DATESMTD function (DAX)
DATESQTD function (DAX)
Get Sample Data
ENDOFMONTH
12/10/2018 • 2 minutes to read

Returns the last date of the month in the current context for the specified column of dates.

Syntax
ENDOFMONTH(<dates>)

Parameters

Term Definition

dates A column that contains dates.

Return value
A table containing a single column and single row with a date value.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that returns the end of the month, for the current context.
To see how this works, create a PivotTable and add the fields CalendarYear and MonthNumberOfYear to the Row
Labels area of the PivotTable. Then add a measure, named EndOfMonth, using the formula defined in the code
section, to the Values area of the PivotTable.

=ENDOFMONTH(DateTime[DateKey])

See also
Date and time functions (DAX)
Time-intelligence functions (DAX)
ENDOFYEAR function (DAX)
ENDOFQUARTER function (DAX)
ENDOFQUARTER
12/10/2018 • 2 minutes to read

Returns the last date of the quarter in the current context for the specified column of dates.

Syntax
ENDOFQUARTER(<dates>)

Parameters

Term Definition

dates A column that contains dates.

Return value
A table containing a single column and single row with a date value.

Remarks
The dates argument can be any of the following:
A reference to a date/time column,
A table expression that returns a single column of date/time values,
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that returns the end of the quarter, for the current context.
To see how this works, create a PivotTable and add the fields CalendarYear and MonthNumberOfYear to the Row
Labels area of the PivotTable. Then add a measure, named EndOfQuarter, using the formula defined in the code
section, to the Values area of the PivotTable.

=ENDOFQUARTER(DateTime[DateKey])

See also
Date and time functions (DAX)
Time-intelligence functions (DAX)
ENDOFYEAR function (DAX)
ENDOFMONTH function (DAX)
ENDOFYEAR
12/10/2018 • 2 minutes to read

Returns the last date of the year in the current context for the specified column of dates.

Syntax
ENDOFYEAR(<dates> [,<year_end_date>])

Parameters

Term Definition

dates A column that contains dates.

year_end_date (optional) A literal string with a date that defines the year-end
date. The default is December 31.

Return value
A table containing a single column and single row with a date value.

Remarks
The dates argument can be any of the following:
A reference to a date/time column,
A table expression that returns a single column of date/time values,
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

The year_end_date parameter is a string literal of a date, in the same locale as the locale of the client where the
workbook was created. The year portion of the date is ignored.
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that returns the end of the fiscal year that ends on June 30, for
the current context.
To see how this works, create a PivotTable and add the field CalendarYear to the Row Labels area of the
PivotTable. Then add a measure, named EndOfFiscalYear, using the formula defined in the code section, to the
Values area of the PivotTable.

=ENDOFYEAR(DateTime[DateKey],"06/30/2004")

See also
Date and time functions (DAX)
Time-intelligence functions (DAX)
ENDOFMONTH function (DAX)
ENDOFQUARTER function (DAX)
FIRSTDATE
12/10/2018 • 2 minutes to read

Returns the first date in the current context for the specified column of dates.

Syntax
FIRSTDATE(<dates>)

Parameters

Term Definition

dates A column that contains dates.

Return value
A table containing a single column and single row with a date value.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values,.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

When the current context is a single date, the date returned by the FIRSTDATE and LASTDATE functions will be
equal.
Technically, the Return value is a table that contains a single column and single value. Therefore, this function can
be used as an argument to any function that requires a table in its arguments. Also, the returned value can be used
whenever a date value is required.
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that obtains the first date when a sale was made in the Internet
sales channel for the current context.
To see how this works, create a PivotTable and add the field CalendarYear to the Row Labels area of the
PivotTable. Then add a measure, named FirstSaleDate, using the formula defined in the code section, to the
Values area of the PivotTable.

=FIRSTDATE('InternetSales_USD'[SaleDateKey])

See also
Date and time functions (DAX)
Time-intelligence functions (DAX)
LASTDATE function (DAX)
FIRSTNONBLANK function (DAX)
Get Sample Data
FIRSTNONBLANK
12/10/2018 • 2 minutes to read

Returns the first value in the column, column, filtered by the current context, where the expression is not blank.

Syntax
FIRSTNONBLANK(<column>,<expression>)

Parameters

TERM DEFINITION

column A column expression.

expression An expression evaluated for blanks for each value of column.

Property Value/Return value


A table containing a single column and single row with the computed first value.

Remarks
The column argument can be any of the following:
A reference to any column.
A table with a single column.
A Boolean expression that defines a single-column table .

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This function is typically used to return the first value of a column for which the expression is not blank. For
example, you could get the last value for which there were sales of a product.
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

See also
LASTNONBLANK function (DAX)
Statistical functions (DAX)
DAX function reference
Get Sample Data
LASTDATE
12/10/2018 • 2 minutes to read

Returns the last date in the current context for the specified column of dates.

Syntax
LASTDATE(<dates>)

Parameters

TERM DEFINITION

dates A column that contains dates.

Return value
A table containing a single column and single row with a date value.

Remarks
The dates argument can be any of the following:
A reference to a date/time column,
A table expression that returns a single column of date/time values,
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

When the current context is a single date, the date returned by the FIRSTDATE and LASTDATE functions will be
equal.
Technically, the Return value is a table that contains a single column and single value. Therefore, this function can
be used as an argument to any function that requires a table in its arguments. Also, the returned value can be used
whenever a date value is required.
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that obtains the last date, for the current context, when a sale was
made in the Internet sales channel.
To see how this works, create a PivotTable and add the field CalendarYear to the Row Labels area of the
PivotTable. Then add a measure, named LastSaleDate, using the formula defined in the code section, to the
Values area of the PivotTable.
=LASTDATE('InternetSales_USD'[SaleDateKey])

See also
Date and time functions (DAX)
Time-intelligence functions (DAX)
FIRSTDATE function (DAX)
LASTNONBLANK function (DAX)
Get Sample Data
LASTNONBLANK
12/10/2018 • 2 minutes to read

Returns the last value in the column, column, filtered by the current context, where the expression is not blank.

Syntax
LASTNONBLANK(<column>,<expression>)

Parameters

Term Definition

column A column expression.

expression An expression evaluated for blanks for each value of column.

Property Value/Return value


A table containing a single column and single row with the computed last value.

Remarks
The column argument can be any of the following:
A reference to any column.
A table with a single column.
A Boolean expression that defines a single-column table

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This function is typically used to return the last value of a column for which the expression is not blank. For
example, you could get the last value for which there were sales of a product.
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

See also
FIRSTNONBLANK function (DAX)
Statistical functions (DAX)
DAX function reference
Get Sample Data
NEXTDAY
12/10/2018 • 2 minutes to read

Returns a table that contains a column of all dates from the next day, based on the first date specified in the dates
column in the current context.

Syntax
NEXTDAY(<dates>)

Parameters

Term Definition

dates A column containing dates.

Return value
A table containing a single column of date values.

Remarks
This function returns all dates from the next day to the first date in the input parameter. For example, if the first
date in the dates argument refers to June 10, 2009; then this function returns all dates equal to June 11, 2009.
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'next day sales' of the internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear and MonthNumberOfYear, to the Row
Labels area of the PivotTable. Then add a measure, named Next Day Sales, using the formula defined in the
code section, to the Values area of the PivotTable.
=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]), NEXTDAY('DateTime'[DateKey]))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
NEXTQUARTER function (DAX)
NEXTMONTH function (DAX)
NEXTYEAR function (DAX)
NEXTMONTH
12/10/2018 • 2 minutes to read

Returns a table that contains a column of all dates from the next month, based on the first date in the dates
column in the current context.

Syntax
NEXTMONTH(<dates>)

Parameters

Term Definition

dates A column containing dates.

Return value
A table containing a single column of date values.

Remarks
This function returns all dates from the next day to the first date in the input parameter. For example, if the first
date in the dates argument refers to June 10, 2009; then this function returns all dates for the month of July,
2009.
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'next month sales' for the Internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear and MonthNumberOfYear, to the Row
Labels area of the PivotTable. Then add a measure, named Next Month Sales, using the formula defined in the
code section, to the Values area of the PivotTable.
=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]), NEXTMONTH('DateTime'[DateKey]))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
NEXTDAY function (DAX)
NEXTQUARTER function (DAX)
NEXTYEAR function (DAX)
Get Sample Data
NEXTQUARTER
12/10/2018 • 2 minutes to read

Returns a table that contains a column of all dates in the next quarter, based on the first date specified in the dates
column, in the current context.

Syntax
NEXTQUARTER(<dates>)

Parameters

Term Definition

dates A column containing dates.

Return value
A table containing a single column of date values.

Remarks
This function returns all dates in the next quarter, based on the first date in the input parameter. For example, if the
first date in the dates column refers to June 10, 2009, this function returns all dates for the quarter July to
September, 2009.
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'next quarter sales' for the Internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear and CalendarQuarter, to the Row
Labels area of the PivotTable. Then add a measure, named Next Quarter Sales, using the formula defined in the
code section to the Values area of the PivotTable.
=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]), NEXTQUARTER('DateTime'[DateKey]))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
NEXTDAY function (DAX)
NEXTMONTH function (DAX)
NEXTYEAR function (DAX)
Get Sample Data
NEXTYEAR
12/10/2018 • 2 minutes to read

Returns a table that contains a column of all dates in the next year, based on the first date in the dates column, in
the current context.

Syntax
NEXTYEAR(<dates>[,<year_end_date>])

Parameters

Term Definition

dates A column containing dates.

year_end_date (optional) A literal string with a date that defines the year-end
date. The default is December 31.

Return value
A table containing a single column of date values.

Remarks
This function returns all dates in the next year, based on the first date in the input column. For example, if the first
date in the dates column refers to the year 2007, this function returns all dates for the year 2008.
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

The year_end_date parameter is a string literal of a date, in the same locale as the locale of the client where the
workbook was created. The year portion of the date is ignored.
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'next year sales' for the Internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear and CalendarQuarter, to the Row
Labels area of the PivotTable. Then add a measure, named Next Year Sales, using the formula defined in the
code section, to the Values area of the PivotTable.

=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]), NEXTYEAR('DateTime'[DateKey]))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
NEXTDAY function (DAX)
NEXTQUARTER function (DAX)
NEXTMONTH function (DAX)
Get Sample Data
OPENINGBALANCEMONTH
12/10/2018 • 2 minutes to read

Evaluates the expression at the first date of the month in the current context.

Syntax
OPENINGBALANCEMONTH(<expression>,<dates>[,<filter>])

Parameters

Parameter Definition

expression An expression that returns a scalar value.

dates A column that contains dates.

filter (optional) An expression that specifies a filter to apply to the


current context.

Return value
A scalar value that represents the expression evaluated at the first date of the month in the current context.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

NOTE
The filter expression has restrictions described in the topic, CALCULATE function (DAX).
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in DirectQuery
models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'Month Start Inventory Value' of the product
inventory.
To see how this works, create a PivotTable and add the fields, CalendarYear, MonthNumberOfYear and
DayNumberOfMonth, to the Row Labels area of the PivotTable. Then add a measure, named Month Start
Inventory Value, using the formula defined in the code section, to the Values area of the PivotTable.

Code
=OPENINGBALANCEMONTH(SUMX(ProductInventory,ProductInventory[UnitCost]*ProductInventory[UnitsBalance]),DateTime
[DateKey])

See also
OPENINGBALANCEYEAR function (DAX)
OPENINGBALANCEQUARTER function (DAX)
Time-intelligence functions (DAX)
CLOSINGBALANCEMONTH function (DAX)
Get Sample Data
OPENINGBALANCEQUARTER
12/10/2018 • 2 minutes to read

Evaluates the expression at the first date of the quarter, in the current context.

Syntax
OPENINGBALANCEQUARTER(<expression>,<dates>[,<filter>])

Parameters

Parameter Definition

expression An expression that returns a scalar value.

dates A column that contains dates.

filte* (optional) An expression that specifies a filter to apply to the


current context.

Return value
A scalar value that represents the expression evaluated at the first date of the quarter in the current context.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values,
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

NOTE
The filter expression has restrictions described in the topic, CALCULATE function (DAX).
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in DirectQuery
models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'Quarter Start Inventory Value' of the product
inventory.
To see how this works, create a PivotTable and add the fields, CalendarYear, CalendarQuarter and
MonthNumberOfYear, to the Row Labels area of the PivotTable. Then add a measure, named Quarter Start
Inventory Value, using the formula defined in the code section, to the Values area of the PivotTable.

Code
=OPENINGBALANCEQUARTER(SUMX(ProductInventory,ProductInventory[UnitCost]*ProductInventory[UnitsBalance]),DateTi
me[DateKey])

See also
OPENINGBALANCEYEAR function (DAX)
OPENINGBALANCEMONTH function (DAX)
Time-intelligence functions (DAX)
CLOSINGBALANCEQUARTER function (DAX)
Get Sample Data
OPENINGBALANCEYEAR
12/10/2018 • 2 minutes to read

Evaluates the expression at the first date of the year in the current context.

Syntax
OPENINGBALANCEYEAR(<expression>,<dates>[,<filter>][,<year_end_date>])

Parameters

Parameter Definition

expression An expression that returns a scalar value.

dates A column that contains dates.

filter (optional) An expression that specifies a filter to apply to the


current context.

year_end_date (optional) A literal string with a date that defines the year-end
date. The default is December 31.

Return value
A scalar value that represents the expression evaluated at the first date of the year in the current context.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

NOTE
The filter expression has restrictions described in the topic, CALCULATE function (DAX).

The year_end_date parameter is a string literal of a date, in the same locale as the locale of the client where the
workbook was created. The year portion of the date is ignored.
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'Year Start Inventory Value' of the product
inventory.
To see how this works, create a PivotTable and add the field, CalendarYear, to the Row Labels area of the
PivotTable. Then add a measure, named Year Start Inventory Value, using the formula defined in the code
section, to the Values area of the PivotTable.

Code
=OPENINGBALANCEYEAR(SUMX(ProductInventory,ProductInventory[UnitCost]*ProductInventory[UnitsBalance]),DateTime[
DateKey])

See also
OPENINGBALANCEQUARTER function (DAX)
OPENINGBALANCEMONTH function (DAX)
Time-intelligence functions (DAX)
CLOSINGBALANCEYEAR function (DAX)
Get Sample Data
PARALLELPERIOD
12/10/2018 • 2 minutes to read

Returns a table that contains a column of dates that represents a period parallel to the dates in the specified dates
column, in the current context, with the dates shifted a number of intervals either forward in time or back in time.

Syntax
PARALLELPERIOD(<dates>,<number_of_intervals>,<interval>)

Parameters

Term Definition

dates A column that contains dates.

number_of_intervals An integer that specifies the number of intervals to add to or


subtract from the dates.

interval The interval by which to shift the dates. The value for interval
can be one of the following: year , quarter , month .

Return value
A table containing a single column of date values.

Remarks
This function takes the current set of dates in the column specified by dates, shifts the first date and the last date
the specified number of intervals, and then returns all contiguous dates between the two shifted dates. If the
interval is a partial range of month, quarter, or year then any partial months in the result are also filled out to
complete the entire interval.
The dates argument can be any of the following:
A reference to a date/time column,
A table expression that returns a single column of date/time values,
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

If the number specified for number_of_intervals is positive, the dates in dates are moved forward in time; if the
number is negative, the dates in dates are shifted back in time.
The interval parameter is an enumeration, not a set of strings; therefore values should not be enclosed in
quotation marks. Also, the values: year , quarter , month should be spelled in full when using them.
The result table includes only dates that appear in the values of the underlying table column.
The PARALLELPERIOD function is similar to the DATEADD function except that PARALLELPERIOD always
returns full periods at the given granularity level instead of the partial periods that DATEADD returns. For example,
if you have a selection of dates that starts at June 10 and finishes at June 21 of the same year, and you want to
shift that selection forward by one month then the PARALLELPERIOD function will return all dates from the next
month (July 1 to July 31); however, if DATEADD is used instead, then the result will include only dates from July 10
to July 21.
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the previous year sales for Internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear and CalendarQuarter, to the Row
Labels area of the PivotTable. Then add a measure, named Previous Year Sales, using the formula defined in the
code section, to the Values area of the PivotTable.

NOTE
The above example uses the table DateTime from the DAX sample workbook. For more information about samples, see Get
Sample Data .

=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]), PARALLELPERIOD(DateTime[DateKey],-1,year))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
DATEADD function (DAX)
Get Sample Data
PREVIOUSDAY
12/10/2018 • 2 minutes to read

Returns a table that contains a column of all dates representing the day that is previous to the first date in the
dates column, in the current context.

Syntax
PREVIOUSDAY(<dates>)

Parameters

Term Definition

dates A column containing dates.

Return value
A table containing a single column of date values.

Remarks
This function determines the first date in the input parameter, and then returns all dates corresponding to the day
previous to that first date. For example, if the first date in the dates argument refers to June 10, 2009; this function
returns all dates equal to June 9, 2009.
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'previous day sales' for the Internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear and MonthNumberOfYear, to the Row
Labels area of the PivotTable. Then add a measure, named Previous Day Sales, using the formula defined in the
code section, to the Values area of the PivotTable.
=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]), PREVIOUSDAY('DateTime'[DateKey]))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
PREVIOUSMONTH function (DAX)
PREVIOUSQUARTER function (DAX)
PREVIOUSYEAR function (DAX)
PREVIOUSMONTH
12/10/2018 • 2 minutes to read

Returns a table that contains a column of all dates from the previous month, based on the first date in the dates
column, in the current context.

Syntax
PREVIOUSMONTH(<dates>)

Parameters

Term Definition

Dates A column containing dates.

Return value
A table containing a single column of date values.

Remarks
This function returns all dates from the previous month, using the first date in the column used as input. For
example, if the first date in the dates argument refers to June 10, 2009, this function returns all dates for the
month of May, 2009.
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'previous month sales' for the Internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear and MonthNumberOfYear, to the Row
Labels area of the PivotTable. Then add a measure, named Previous Month Sales, using the formula defined in
the code section, to the Values area of the PivotTable.
=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]), PREVIOUSMONTH('DateTime'[DateKey]))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
PREVIOUSDAY function (DAX)
PREVIOUSQUARTER function (DAX)
PREVIOUSYEAR function (DAX)
Get Sample Data
PREVIOUSQUARTER
12/10/2018 • 2 minutes to read

Returns a table that contains a column of all dates from the previous quarter, based on the first date in the dates
column, in the current context.

Syntax
PREVIOUSQUARTER(<dates>)

Parameters

Term Definition

dates A column containing dates.

Return value
A table containing a single column of date values.

Remarks
This function returns all dates from the previous quarter, using the first date in the input column. For example, if
the first date in the dates argument refers to June 10, 2009, this function returns all dates for the quarter January
to March, 2009.
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'previous quarter sales' for Internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear and CalendarQuarter, to the Row
Labels area of the PivotTable. Then add a measure, named Previous Quarter Sales, using the formula defined in
the code section, to the Values area of the PivotTable.
=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]), PREVIOUSQUARTER('DateTime'[DateKey]))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
PREVIOUSMONTH function (DAX)
PREVIOUSDAY function (DAX)
PREVIOUSYEAR function (DAX)
Get Sample Data
PREVIOUSYEAR
12/10/2018 • 2 minutes to read

Returns a table that contains a column of all dates from the previous year, given the last date in the dates column,
in the current context.

Syntax
PREVIOUSYEAR(<dates>[,<year_end_date>])

Parameters

Term Definition

dates A column containing dates.

year_end_date (optional) A literal string with a date that defines the year-end
date. The default is December 31.

Return value
A table containing a single column of date values.

Remarks
This function returns all dates from the previous year given the latest date in the input parameter. For example, if
the latest date in the dates argument refers to the year 2009, then this function returns all dates for the year of
2008, up to the specified year_end_date.
The dates argument can be any of the following:
A reference to a date/time column,
A table expression that returns a single column of date/time values,
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

The year_end_date parameter is a string literal of a date, in the same locale as the locale of the client where the
workbook was created. The year portion of the date is ignored.
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the previous year sales for the Internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear and CalendarQuarter, to the Row
Labels area of the PivotTable. Then add a measure, named Previous Year Sales, using the formula defined in the
code section, to the Values area of the PivotTable.

=CALCULATE(SUM(InternetSales_USD[SalesAmount_USD]), PREVIOUSYEAR('DateTime'[DateKey]))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
PREVIOUSMONTH function (DAX)
PREVIOUSDAY function (DAX)
PREVIOUSQUARTER function (DAX)
SAMEPERIODLASTYEAR
12/10/2018 • 2 minutes to read

Returns a table that contains a column of dates shifted one year back in time from the dates in the specified dates
column, in the current context.

Syntax
SAMEPERIODLASTYEAR(<dates>)

Parameters

Term Definition

dates A column containing dates.

Property Value/Return value


A single-column table of date values.

Remarks
The dates argument can be any of the following:
A reference to a date/time column,
A table expression that returns a single column of date/time values,
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

The dates returned are the same as the dates returned by this equivalent formula:
DATEADD(dates, -1, year)

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the previous year sales of the Reseller sales.
To see how this works, create a PivotTable and add the fields, CalendarYear to the Row Labels area of the
PivotTable. Then add a measure, named Previous Year Sales, using the formula defined in the code section, to the
Values area of the PivotTable.
=CALCULATE(SUM(ResellerSales_USD[SalesAmount_USD]), SAMEPERIODLASTYEAR(DateTime[DateKey]))

See also
Time-intelligence functions (DAX)
Date and time functions (DAX)
PREVIOUSYEAR function (DAX)
PARALLELPERIOD function (DAX)
STARTOFMONTH
12/10/2018 • 2 minutes to read

Returns the first date of the month in the current context for the specified column of dates.

Syntax
STARTOFMONTH(<dates>)

Parameters

Term Definition

dates A column that contains dates.

Return value
A table containing a single column and single row with a date value.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that returns the start of the month, for the current context.
To see how this works, create a PivotTable and add the fields CalendarYear and MonthNumberOfYear to the Row
Labels area of the PivotTable. Then add a measure, named StartOfMonth, using the formula defined in the code
section, to the Values area of the PivotTable.

=STARTOFMONTH(DateTime[DateKey])

See also
Date and time functions (DAX)
Time-intelligence functions (DAX)
STARTOFYEAR function (DAX)
STARTOFQUARTER function (DAX)
STARTOFQUARTER
12/10/2018 • 2 minutes to read

Returns the first date of the quarter in the current context for the specified column of dates.

Syntax
STARTOFQUARTER(<dates>)

Parameters

TERM DEFINITION

dates A column that contains dates.

Return value
A table containing a single column and single row with a date value.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that returns the start of the quarter, for the current context.
To see how this works, create a PivotTable and add the fields CalendarYear and MonthNumberOfYear to the Row
Labels area of the PivotTable. Then add a measure, named StartOfQuarter, using the formula defined in the code
section, to the Values area of the PivotTable.

=STARTOFQUARTER(DateTime[DateKey])

See also
Date and time functions (DAX)
Time-intelligence functions (DAX)
STARTOFYEAR function (DAX)
STARTOFMONTH function (DAX)
STARTOFYEAR
12/10/2018 • 2 minutes to read

Returns the first date of the year in the current context for the specified column of dates.

Syntax
STARTOFYEAR(<dates>)

Parameters

TERM DEFINITION

dates A column that contains dates.

YearEndDate (Optional) A year end date value.

Return value
A table containing a single column and single row with a date value.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that returns the start of the year, for the current context.
To see how this works, create a PivotTable and add the fields CalendarYear and MonthNumberOfYear to the Row
Labels area of the PivotTable. Then add a measure, named StartOfYear, using the formula defined in the code
section, to the Values area of the PivotTable.

=STARTOFYEAR(DateTime[DateKey])

See also
Date and time functions (DAX)
Time-intelligence functions (DAX)
STARTOFQUARTER function (DAX)
STARTOFMONTH function (DAX)
TOTALMTD
12/10/2018 • 2 minutes to read

Evaluates the value of the expression for the month to date, in the current context.

Syntax
TOTALMTD(<expression>,<dates>[,<filter>])

Parameters

PARAMETER DEFINITION

expression An expression that returns a scalar value.

dates A column that contains dates.

filter (optional) An expression that specifies a filter to apply to the


current context.

Return value
A scalar value that represents the expression evaluated for the dates in the current month-to-date, given the dates
in dates.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

NOTE
The filter expression has restrictions described in the topic, CALCULATE function (DAX).

This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'month running total' or 'month running sum'
for the Internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear, MonthNumberOfYear and
DayNumberOfMonth, to the Row Labels area of the PivotTable. Then add a measure, named Month-to-date
Total, using the formula defined in the code section, to the Values area of the PivotTable.

Code
=TOTALMTD(SUM(InternetSales_USD[SalesAmount_USD]),DateTime[DateKey])

See also
ALL function (DAX)
CALCULATE function (DAX)
TOTALYTD function (DAX)
TOTALQTD function (DAX)
Get Sample Data
TOTALQTD
12/10/2018 • 2 minutes to read

Evaluates the value of the expression for the dates in the quarter to date, in the current context.

Syntax
TOTALQTD(<expression>,<dates>[,<filter>])

Parameters

PARAMETER DEFINITION

expression An expression that returns a scalar value.

dates A column that contains dates.

filter (optional) An expression that specifies a filter to apply to the


current context.

Return value
A scalar value that represents the expression evaluated for all dates in the current quarter to date, given the dates
in dates.

Remarks
The dates argument can be any of the following:
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

NOTE
The filter expression has restrictions described in the topic, CALCULATE function (DAX).
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in DirectQuery
models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'quarter running total' or 'quarter running
sum' for the Internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear, CalendarQuarter and
MonthNumberOfYear, to the Row Labels area of the PivotTable. Then add a measure, named Quarter-to-date
Total, using the formula defined in the code section, to the Values area of the PivotTable.

Code
=TOTALQTD(SUM(InternetSales_USD[SalesAmount_USD]),DateTime[DateKey])

See also
ALL function (DAX)
CALCULATE function (DAX)
TOTALYTD function (DAX)
TOTALMTD function (DAX)
Get Sample Data
TOTALYTD
12/10/2018 • 2 minutes to read

Evaluates the year-to-date value of the expression in the current context.

Syntax
TOTALYTD(<expression>,<dates>[,<filter>][,<year_end_date>])

Parameters

PARAMETER DEFINITION

expression An expression that returns a scalar value.

dates A column that contains dates.

filter (optional) An expression that specifies a filter to apply to the


current context.

year_end_date (optional) A literal string with a date that defines the year-end
date. The default is December 31.

Return value
A scalar value that represents the expression evaluated for the current year-to-date dates.

Remarks
The dates argument can be any of the following:
A reference to a date/time column,
A table expression that returns a single column of date/time values,
A Boolean expression that defines a single-column table of date/time values.

NOTE
Constraints on Boolean expressions are described in the topic, CALCULATE function (DAX).

NOTE
The filter expression has restrictions described in the topic, CALCULATE function (DAX).

The year_end_date parameter is a string literal of a date, in the same locale as the locale of the client where the
workbook was created. The year portion of the date is not required and is ignored.
For example, the following formula specifies a (fiscal) year_end_date of 6/30 in an EN -US locale workbook.
=TOTALYTD(SUM(InternetSales_USD[SalesAmount_USD]),DateTime[DateKey], ALL(‘DateTime’), “6/30”)

In this example, year_end_date can be specified as “6/30”, “Jun 30”, “30 June”, or any string that resolves to a
month/day. However, it is recommended you specify year_end_date using “month/day” (as shown) to ensure the
string resolves to a date.
This DAX function is not supported for use in DirectQuery mode. For more information about limitations in
DirectQuery models, see https://go.microsoft.com/fwlink/?LinkId=219172.

Example
The following sample formula creates a measure that calculates the 'year running total' or 'year running sum' for
the Internet sales.
To see how this works, create a PivotTable and add the fields, CalendarYear, CalendarQuarter, and
MonthNumberOfYear, to the Row Labels area of the PivotTable. Then add a measure, named Year-to-date Total,
using the formula defined in the code section, to the Values area of the PivotTable.

Code
=TOTALYTD(SUM(InternetSales_USD[SalesAmount_USD]),DateTime[DateKey])

See also
ALL function (DAX)
CALCULATE function (DAX)
DATESYTD function (DAX)
TOTALMTD function (DAX)
TOTALQTD function (DAX)
Get Sample Data
Filter functions
12/10/2018 • 2 minutes to read

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.

In this section
ADDMISSINGITEMS
ALL
ALLEXCEPT
ALLNOBLANKROW
ALLSELECTED
CALCULATE
CALCULATETABLE
CROSSFILTER function
DISTINCT
EARLIER
EARLIEST
FILTER
FILTERS
HASONEFILTER
HASONEVALUE
ISCROSSFILTERED
ISFILTERED
KEEPFILTERS
RELATED
RELATEDTABLE
SELECTEDVALUE
SUBSTITUTEWITHINDEX
USERELATIONSHIP
VALUES
ADDMISSINGITEMS
12/10/2018 • 2 minutes to read

Adds combinations of items from multiple columns to a table if they do not already exist. The determination of
which item combinations to add is based on referencing source columns which contain all the possible values for
the columns.
To determine the combinations of items from different columns to evaluate: AutoExist is applied for columns
within the same table while CrossJoin is applied across different tables.
The ADDMISSINGITEMS function will return BLANK values for the IsSubtotal columns of blank rows it adds.

Syntax
ADDMISSINGITEMS(<showAllColumn>[, <showAllColumn>]…, <table>, <groupingColumn>[, <groupingColumn>]…[,
filterTable]…)

ADDMISSINGITEMS(<showAllColumn>[, <showAllColumn>]…, <table>, [ROLLUPISSUBTOTAL(]<groupingColumn>[,


<isSubtotal_columnName>][, <groupingColumn>][, <isSubtotal_columnName>]…[)], [, filterTable]…)

Parameters

TERM DEFINITION

showAllColumn A column for which to return items with no data for the
measures used.

table A table containing all items with data (NON EMPTY) for the
measures used.

groupingColumn A column which is used to group by in the supplied table


argument.

isSubtotal_columnName A Boolean column in the supplied table argument which


contains ISSUBTOTAL values for the corresponding
groupingColumn column.

filterTable A table representing filters to include in the logic for


determining whether to add specific combinations of items
with no data. Used to avoid having ADDMISSINGITEMS add in
item combinations which are not present because they were
removed by a filter.

ADDMISSINGITEMS with ROLLUPGROUP


ROLLUPGROUP is used inside the ROLLUPISSUBTOTAL function to reflect ROLLUPGROUPs present in the
supplied table argument.
Restrictions
If ROLLUPISSUBTOTAL was used to define the supplied table argument (or the equivalent rows and
ISSUBTOTAL columns were added by some other means), ROLLUPISSUBTOTAL must be used with the
same arguments within ADDMISSINGITEMS. This is also true for ROLLUPGROUP if it was used with
ROLLUPISSUBTOTAL to define the supplied table argument.
The ADDMISSINGITEMS function requires that, if ROLLUPISSUBTOTAL was used to define the supplied
table argument, ISSUBTOTAL columns corresponding to each group by column, or ROLLUPGROUP, are
present in the supplied table argument. Also, the names of the ISSUBTOTAL columns must be supplied in
the ROLLUPISSUBTOTAL function inside ADDMISSINGITEMS and they must match names of Boolean
columns in the supplied table argument. This enables the ADDMISSINGITEMS function to identify BLANK
values stemming from the fact that a row is a subtotal row from other BLANK values.
If ROLLUPGROUP was used with ROLLUPISSUBTOTAL to define the supplied table argument, exactly one
ISSUBTOTAL column name must be supplied per ROLLUPGROUP and it must match the corresponding
ISSUBTOTAL column name in the supplied table argument.

Example
Add blank rows for columns with "show items with no data" turned on. The ADDMISSINGITEMS function will
return NULLs/BLANKs for the IsSubtotal columns of blank rows it adds.

VAR 'RowHeadersShowAll' =
CALCULATETABLE
(
ADDMISSINGITEMS
(
[Sales Territory Country],
[Sales Territory Region],
'RowHeadersInCrossTab',
ROLLUPISSUBTOTAL
(
[Sales Territory Group],
[Subtotal for Sales Territory Group],
[Sales Territory Country],
[Subtotal for Sales Territory Country],
[Sales Territory Region],
[Subtotal for Sales Territory Region]
),
'RowHeaders'
),
'DateFilter','TerritoryFilter'
)

Example with ROLLUPGROUP


VAR 'RowHeadersShowAll' =
CALCULATETABLE
(
ADDMISSINGITEMS
(
[Sales Territory Country],
[Sales Territory Region],
'RowHeadersInCrossTab',
ROLLUPISSUBTOTAL
(
ROLLUPGROUP
(
[Sales Territory Group],
[Sales Territory Country]
),
[Subtotal for Sales Territory Country],
[Sales Territory Region],
[Subtotal for Sales Territory Region]
),
'RowHeaders'
)
ALL
12/10/2018 • 7 minutes to read

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
ALL( {<table> | <column>[, <column>[, <column>[,…]]]} )

Parameters

TERM DEFINITION

table The table that you want to clear filters on.

column The column that you want to clear filters on.

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.
<Topic Status: Some information in this topic is pre-release and subject to change in future releases. Pre-
release information describes new features or changes to existing features in Microsoft SQL Server 2016.In
cases where [Column] is marked as Date column by using Mark as Date table
As described in the following table, you can use the ALL and ALLEXCEPT functions in different scenarios.

FUNCTION AND USAGE DESCRIPTION

ALL(Table) Removes all filters from the specified table. In effect,


ALL(Table) returns all of the values in the table, removing any
filters from the context that otherwise might have been
applied.

This function is useful when you are working with many levels
of grouping, and want to create a calculation that creates a
ratio of an aggregated value to the total value. The first
example demonstrates this scenario.
FUNCTION AND USAGE DESCRIPTION

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.

Example
Calculate Ratio of Category Sales to Total Sales
Assume that you want to find the amount of sales for the current cell, in your PivotTable, divided by the total
sales for all resellers. To ensure that the denominator is the same regardless of how the PivotTable user might be
filtering or grouping the data, you define a formula that uses ALL to create the correct grand total.
The following table shows the results when a new measure, All Reseller Sales Ratio, 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, drag the measure,
All Reseller Sales Ratio, to the Values area of the Pivot Table. To view the results as percentages, use the
formatting features of Excel to apply a percentage number formatting to the cells that contains the measure.

ALL RESELLER
SALES COLUMN LABELS

Row Labels Accessories Bikes Clothing Components Grand Total

2005 0.02% 9.10% 0.04% 0.75% 9.91%

2006 0.11% 24.71% 0.60% 4.48% 29.90%

2007 0.36% 31.71% 1.07% 6.79% 39.93%

2008 0.20% 16.95% 0.48% 2.63% 20.26%

Grand Total 0.70% 82.47% 2.18% 14.65% 100.00%

Formula

=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.

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
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 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.

RESELLER SALES
YEAR COLUMN LABELS

Row Labels Accessories Bikes Clothing Components Grand Total

2005 3.48% 11.03% 1.91% 5.12% 9.91%

2006 16.21% 29.96% 27.29% 30.59% 29.90%

2007 51.62% 38.45% 48.86% 46.36% 39.93%

2008 28.69% 20.56% 21.95% 17.92% 20.26%

Grand Total 100.00% 100.00% 100.00% 100.00% 100.00%

Formula

=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.

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
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 n, and then divide the resulting
value by the sum of sales for the year n 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.

RESELLER SALES
CATEGORYNAME COLUMN LABELS

Row Labels Accessories Bikes Clothing Components Grand Total

2005 0.25% 91.76% 0.42% 7.57% 100.00%

2006 0.38% 82.64% 1.99% 14.99% 100.00%

2007 0.90% 79.42% 2.67% 17.01% 100.00%

2008 0.99% 83.69% 2.37% 12.96% 100.00%

Grand Total 0.70% 82.47% 2.18% 14.65% 100.00%

Formula

=SUMX(ResellerSales_USD, ResellerSales_USD[SalesAmount_USD])/CALCULATE( SUM(


ResellerSales_USD[SalesAmount_USD]), ALL(ProductCategory[ProductCategoryName]))

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 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.

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 functions (DAX)
ALL function (DAX)
ALLEXCEPT function (DAX)
FILTER function (DAX)
ALLEXCEPT
12/10/2018 • 2 minutes to read

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

table The table over which all context filters are removed, except
filters on those columns that are specified in subsequent
arguments.

column The column for which context filters must be preserved.

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.

FUNCTION AND USAGE DESCRIPTION

ALL(Table) Removes all filters from the specified table. In effect,


ALL(Table) returns all of the values in the table, removing any
filters from the context that otherwise might have been
applied.

This function is useful when you are working with many levels
of grouping, and want to create a calculation that creates a
ratio of an aggregated value to the total value.

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.
FUNCTION AND USAGE DESCRIPTION

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.

Example
The following example presents a formula that you can use in 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 .

=CALCULATE(SUM(ResellerSales_USD[SalesAmount_USD]), ALLEXCEPT(DateTime, DateTime[CalendarYear]))

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 functions (DAX)
ALL function (DAX)
FILTER function (DAX)
ALLNOBLANKROW
12/10/2018 • 4 minutes to read

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>[, <column>[, <column>[,…]]]} )

Parameters

TERM DEFINITION

table The table over which all context filters are removed.

column A column over which all context filters are removed.

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:

FUNCTION AND USAGE DESCRIPTION

ALL(Column) Removes all filters from the specified column in the table; all
other filters in the table, over other columns, still apply.

ALL(Table) Removes all filters from the specified table.

ALLEXCEPT(Table,Col1,Col2...) Overrides all context filters in the table except over the
specified columns.

ALLNOBLANK(table|column) 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

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
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 Power Pivot 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 ALLNOBLANK
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.
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:

ROW LABELS COUNTROWS ALLNOBLANK OF DATETIME COUNTROWS ALL OF DATETIME

2005 1280 1281

2006 1280 1281


ROW LABELS COUNTROWS ALLNOBLANK OF DATETIME COUNTROWS ALL OF DATETIME

2007 1280 1281

2008 1280 1281

1280 1281

Grand Total 1280 1281

The results show a difference of 1 row in the table rows count. However, if you open the Power Pivot 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:

COUNTROWS ALLNOBLANKROW OF
ROW LABELS RESELLERSALES_USD COUNTROWS ALL OF RESELLERSALES_USD

2005 60856 60856

2006 60856 60856

2007 60856 60856

2008 60856 60856

60856 60856

Grand Total 60856 60856

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.

// Countrows ALLNOBLANK of datetime


= COUNTROWS(ALLNOBLANKROW('DateTime'))

// Countrows ALL of datetime


= COUNTROWS(ALL('DateTime'))

// Countrows ALLNOBLANKROW of ResellerSales_USD


=COUNTROWS(ALLNOBLANKROW('ResellerSales_USD'))

// Countrows ALL of ResellerSales_USD


=COUNTROWS(ALL('ResellerSales_USD'))

See also
Filter functions (DAX)
ALL function (DAX)
FILTER function (DAX)
ALLSELECTEDAX)
12/10/2018 • 4 minutes to read

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

TERM DEFINITION

tableName The name of an existing table, using standard DAX syntax. This
parameter cannot be an expression. This parameter is
optional.

columnName The name of an existing column using standard DAX syntax,


usually fully qualified. It cannot be an expression. This
parameter is optional.

Return value
The context of the query without any column and row filters.

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
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.
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())
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]

After executing the above expression in SQL Server Management Studio against AdventureWorks DW Tabular
Model, you obtain the following results:

[RESELLER
[RESELLER VISUAL TOTAL
VISUAL TOTAL FOR ALL OF
[PRODUCT [RESELLER FOR ALL OF PRODUCT
CATEGORY [CALENDAR SALES [RESELLER [RESELLER CALENDAR CATEGORY
NAME] YEAR] AMOUNT] GRAND TOTAL] VISUAL TOTAL] YEAR] NAME]

Accessories 2000 80450596.98 877006.7987 38786.018


23

Accessories 2001 80450596.98 877006.7987 38786.018


23

Accessories 2002 625.7933 80450596.98 877006.7987 38786.018 91495.3104


23

Accessories 2003 26037.3132 80450596.98 877006.7987 38786.018 572927.0136


23

Accessories 2004 12122.9115 80450596.98 877006.7987 38786.018 212584.4747


23

Accessories 2005 80450596.98 877006.7987 38786.018


23
[RESELLER
[RESELLER VISUAL TOTAL
VISUAL TOTAL FOR ALL OF
[PRODUCT [RESELLER FOR ALL OF PRODUCT
CATEGORY [CALENDAR SALES [RESELLER [RESELLER CALENDAR CATEGORY
NAME] YEAR] AMOUNT] GRAND TOTAL] VISUAL TOTAL] YEAR] NAME]

Accessories 2006 80450596.98 877006.7987 38786.018


23

Bikes 2000 80450596.98 877006.7987 689287.7939


23

Bikes 2001 80450596.98 877006.7987 689287.7939


23

Bikes 2002 73778.938 80450596.98 877006.7987 689287.7939 91495.3104


23

Bikes 2003 439771.4136 80450596.98 877006.7987 689287.7939 572927.0136


23

Bikes 2004 175737.4423 80450596.98 877006.7987 689287.7939 212584.4747


23

Bikes 2005 80450596.98 877006.7987 689287.7939


23

Bikes 2006 80450596.98 877006.7987 689287.7939


23

Clothing 2000 80450596.98 877006.7987 95090.7757


23

Clothing 2001 80450596.98 877006.7987 95090.7757


23

Clothing 2002 12132.4334 80450596.98 877006.7987 95090.7757 91495.3104


23

Clothing 2003 58234.2214 80450596.98 877006.7987 95090.7757 572927.0136


23

Clothing 2004 24724.1209 80450596.98 877006.7987 95090.7757 212584.4747


23

Clothing 2005 80450596.98 877006.7987 95090.7757


23

Clothing 2006 80450596.98 877006.7987 95090.7757


23

Components 2000 80450596.98 877006.7987 53842.2111


23

Components 2001 80450596.98 877006.7987 53842.2111


23
[RESELLER
[RESELLER VISUAL TOTAL
VISUAL TOTAL FOR ALL OF
[PRODUCT [RESELLER FOR ALL OF PRODUCT
CATEGORY [CALENDAR SALES [RESELLER [RESELLER CALENDAR CATEGORY
NAME] YEAR] AMOUNT] GRAND TOTAL] VISUAL TOTAL] YEAR] NAME]

Components 2002 4958.1457 80450596.98 877006.7987 53842.2111 91495.3104


23

Components 2003 48884.0654 80450596.98 877006.7987 53842.2111 572927.0136


23

Components 2004 80450596.98 877006.7987 53842.2111 212584.4747


23

Components 2005 80450596.98 877006.7987 53842.2111


23

Components 2006 80450596.98 877006.7987 53842.2111


23

The columns in the report are:


Reseller Sales Amount
The actual value of Reseller Sales for the year and product category. This value appears in a cell in the center of
your report, at the intersection of year and catergory.
Reseller Visual Total for All of Calendar Year
The total value for a product category across all years. This value appears at the end of a column or row for a given
product category and across all years in the report.
Reseller Visual Total for All of Product Category Name
The total value for a year across all product categories. This value appears at the end of a column or row for a
given year and across all product categories in the report.
Reseller Visual Total
The total value for all years and product categories. This value usually appears in the bottom rightmost corner of
the table.
Reseller Grand Total
This is the grand total for all reseller sales, before any filter has been applied; you should notice the difference with
[Reseller Visual Total]. You do remember that this report includes two (2) filters, one on Product Category Group
and the other in Promotion Type.

NOTE
if you have explicit filters in your expression, those filters are also applied to the expression.
CALCULATE
12/10/2018 • 2 minutes to read

Evaluates an expression in a context that is modified by the specified filters.

Syntax
CALCULATE(<expression>,<filter1>,<filter2>…)

Parameters

TERM DEFINITION

expression The expression to be evaluated.

filter1, filter2,… (optional) A comma separated list of Boolean


expression or a table expression that defines a filter.

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
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 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.

ALL RESELLER COLUMN


SALES LABELS

Row Labels Accessories Bikes Clothing Components Grand Total

2005 0.02% 9.10% 0.04% 0.75% 9.91%

2006 0.11% 24.71% 0.60% 4.48% 29.90%

2007 0.36% 31.71% 1.07% 6.79% 39.93%

2008 0.20% 16.95% 0.48% 2.63% 20.26%

Grand Total 0.70% 82.47% 2.18% 14.65% 100.00%

=( SUM('ResellerSales_USD'[SalesAmount_USD]))
/CALCULATE( SUM('ResellerSales_USD'[SalesAmount_USD])
,ALL('ResellerSales_USD'))

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 (DAX)
Filter functions (DAX)
CALCULATETABLE
12/10/2018 • 2 minutes to read

Evaluates a table expression in a context modified by the given filters.

Syntax
CALCULATETABLE(<expression>,<filter1>,<filter2>,…)

Parameters

TERM DEFINITION

Expression** The table expression to be evaluated

filter1, filter2,… A Boolean expression or a table expression that defines a filter

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
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.
INTERNET CALCULATETABLE 2006 INTERNET SALES TO 2006
ROW LABELS SALESAMOUNT_USD INTERNET SALES RATIO

2005 $2,627,031.40 $5,681,440.58 0.46

2006 $5,681,440.58 $5,681,440.58 1.00

2007 $8,705,066.67 $5,681,440.58 1.53

2008 $9,041,288.80 $5,681,440.58 1.59

Grand Total $26,054,827.45 $5,681,440.58 4.59

=SUMX( CALCULATETABLE('InternetSales_USD', 'DateTime'[CalendarYear]=2006)


, [SalesAmount_USD])

See also
RELATEDTABLE function (DAX)
Filter functions (DAX)
CROSSFILTER
12/10/2018 • 2 minutes to read

Specifies the cross-filtering direction to be used in a calculation for a relationship that exists between two columns.

Syntax
CROSSFILTER(<columnName1>, <columnName2>, <direction>)

Parameters

TERM DEFINITION

columnName1 The name of an existing column, using standard DAX syntax


and fully qualified, that usually represents the many side of
the relationship to be used; if the arguments are given in
reverse order the function will swap them before using them.
This argument cannot be an expression.

columnName2 The name of an existing column, using standard DAX syntax


and fully qualified, that usually represents the one side or
lookup side of the relationship to be used; if the arguments
are given in reverse order the function will swap them before
using them. This argument cannot be an expression.

Direction The cross-filter direction to be used. Must be one of the


following:
none
No cross-filtering occurs along this relationship

one - Filters on the one or lookup side of the side of the


relationship filter the many side.

both -
Filters on either side filter the other

none - No cross-filtering occurs along this relationship

Return value
The function returns no value; the function only sets the cross-filtering direction for the indicated relationship, for
the duration of the query.

Remarks
In the case of a 1:1 relationship, there is no difference between the one and both direction.
CROSSFILTER 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.
CROSSFILTER uses existing relationships in the model, identifying relationships by their ending point
columns.
In CROSSFILTER, the cross-filtering setting of a relationship is not important; that is, whether the
relationship is set to filter one, or both directions in the model does not affect the usage of the function.
CROSSFILTER will override any existing cross-filtering setting.
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.
If CALCULATE expressions are nested, and more than one CALCULATE expression contains a
CROSSFILTER function, then the innermost CROSSFILTER is the one that prevails in case of a conflict or
ambiguity.

Example
In the following model diagram, both DimProduct and DimDate have a single direction relationship with
FactOnlineSales.

By default, we cannot get the Count of Products sold by year:

There are two ways to get the count of products by year:


Turn on bi-directional cross-filtering on the relationship. This will change how filters work for all data
between these two tables.
Use the CROSSFILTER function to change how the relationships work for just this measure.
When using DAX, we can use the CROSSFILTER function to change how the cross-filter direction behaves
between two columns defined by a relationship. In this case, the DAX expression looks like this:
BiDi:= CALCULATE ([Distinct Count of ProductKey], CROSSFILTER(FactInternetSales[ProductKey],
DimProduct[ProductKey] , Both))
By using the CROSSFILTER function in our measure expression, we get the expected results.
DISTINCT (column)
12/10/2018 • 2 minutes to read

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

column The column from which unique values are to be returned. Or,
an expression that returns a column.

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
There is another version of the DISTINCT function, DISTINCT (table), that returns a table by removing duplicate
rows from another table or expression..
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
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.

=COUNTROWS(DISTINCT(InternetSales_USD[CustomerKey]))
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.

UNIQUE INTERNET
CUSTOMERS COLUMN LABELS

Row Labels Accessories Bikes Clothing Grand Total

2005 1013 1013

2006 2677 2677

2007 6792 4875 2867 9309

2008 9435 5451 4196 11377

Grand Total 15114 9132 6852 18484

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.

See also
Filter functions (DAX)
FILTER function (DAX)
RELATED function (DAX)
VALUES function (DAX)
DISTINCT (table)
12/10/2018 • 2 minutes to read

Returns a table by removing duplicate rows from another table or expression.

Syntax
DISTINCT(<table>)

Parameters

TERM DEFINITION

table The table from which unique rows are to be returned. The
table can also be an expression that results in a table.

Return value
A table containing only distinct rows.

Related functions
There is another version of the DISTINCT function, DISTINCT (column), that takes a column name as input
parameter.

Example
The following query:

EVALUATE DISTINCT( { (1, "A"), (2, "B"), (1, "A") } )

Returns table:

[VALUE1] [VALUE2]

1 A

2 B

See also
Filter functions (DAX)
DISTINCT (column) (DAX)
FILTER function (DAX)
RELATED function (DAX)
VALUES function (DAX)
EARLIER
12/10/2018 • 3 minutes to read

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

column A column or expression that resolves to a column.

num (Optional) A positive number to the outer evaluation pass.

The next evaluation level out is represented by 1; two levels


out is represented by 2 and so on.

When omitted default value is 1.

Property Value/Return value


The current value of row, from column, at number of outer evaluation passes.

Exceptions
Description of errors

Remarks
EARLIER succeeds if there is a row context prior to the beginning of the table scan. Otherwise it returns an error.
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
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.

ENGLISHPRODUCTSUBCATEGO
PRODUCTSUBCATEGORYKEY RYNAME TOTALSUBCATEGORYSALES SUBCATEGORYRANKING

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

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
ENGLISHPRODUCTSUBCATEGO
PRODUCTSUBCATEGORYKEY RYNAME TOTALSUBCATEGORYSALES SUBCATEGORYRANKING

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

Creating a Rank Value


One way to obtain a rank value for a given value in a row is to count the number of rows, in the same table, that
have a value larger (or smaller) than the one that is being compared. This technique returns a blank or zero value
for the highest value in the table, 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.

= COUNTROWS(FILTER(ProductSubcategory, EARLIER(ProductSubcategory[TotalSubcategorySales])
<ProductSubcategory[TotalSubcategorySales]))+1

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
EARLIEST function (DAX)
Filter functions (DAX)
EARLIEST
12/10/2018 • 2 minutes to read

Returns the current value of the specified column in an outer evaluation pass of the specified column.

Syntax
EARLIEST(<column>)

Parameters

TERM DEFINITION

column A reference to a column.

Property Value/Return value


A column with filters removed.

Remarks
The EARLIEST function is similar to EARLIER, but lets you specify one additional level of recursion.

Example
The current sample data does not support this scenario.

=EARLIEST(<column>)

See also
EARLIER function (DAX)
Filter functions (DAX)
FILTER
12/10/2018 • 2 minutes to read

Returns a table that represents a subset of another table or expression.

Syntax
FILTER(<table>,<filter>)

Parameters

TERM DEFINITION

table The table to be filtered. The table can also be an expression


that results in a table.

filter A Boolean expression that is to be evaluated for each row of


the table. For example, [Amount] > 0 or
[Region] = "France"

Return value
A table containing only the filtered rows.

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
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
ROW LABELS INTERNET SALES NON USA INTERNET SALES

Australia $4,999,021.84 $4,999,021.84

Canada $1,343,109.10 $1,343,109.10

France $2,490,944.57 $2,490,944.57

Germany $2,775,195.60 $2,775,195.60

United Kingdom $5,057,076.55 $5,057,076.55

United States $9,389,479.79

Grand Total $26,054,827.45 $16,665,347.67

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
NON USA INTERNET
SALES COLUMN LABELS

Row Labels Accessories Bikes Clothing Grand Total

2005 $1,526,481.95 $1,526,481.95

2006 $3,554,744.04 $3,554,744.04

2007 $156,480.18 $5,640,106.05 $70,142.77 $5,866,729.00

2008 $228,159.45 $5,386,558.19 $102,675.04 $5,717,392.68

Grand Total $384,639.63 $16,107,890.23 $172,817.81 $16,665,347.67

SUMX(FILTER('InternetSales_USD', RELATED('SalesTerritory'[SalesTerritoryCountry])<>"United States")


,'InternetSales_USD'[SalesAmount_USD])

See also
Filter functions (DAX)
ALL function (DAX)
ALLEXCEPT function (DAX)
FILTERS
12/10/2018 • 2 minutes to read

Returns the values that are directly applied as filters to columnName.

Syntax
FILTERS(<columnName>)

Parameters

TERM DESCRIPTION

columnName The name of an existing column, using standard DAX syntax.


It cannot be an expression.

Return value
The values that are directly applied as filters to columnName.

Remarks
Example
The following example shows how to determine the number of direct filters a column has.

=COUNTROWS(FILTERS(ResellerSales_USD[ProductKey]))

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
12/10/2018 • 2 minutes to read

Returns TRUE when the number of directly filtered values on columnName is one; otherwise returns FALSE.

Syntax
HASONEFILTER(<columnName>)

Parameters

TERM DEFINITION

columnName The name of an existing column, using standard DAX syntax.


It cannot be an expression.

Return value
TRUE when the number of directly filtered values on columnName is one; otherwise returns FALSE.

Remarks
1. This function is similar to HASONEVALUE () with the difference that HASONEVALUE () works based on cross-
filters while HASONEFILTER () works by a direct filter.

Example
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]).

=IF(HASONEFILTER(ResellerSales_USD[ProductKey]),FILTERS(ResellerSales_USD[ProductKey]),BLANK())
HASONEVALUE
12/10/2018 • 2 minutes to read

Returns TRUE when the context for columnName has been filtered down to one distinct value only. Otherwise is
FALSE.

Syntax
HASONEVALUE(<columnName>)

Parameters

TERM DEFINITION

columnName The name of an existing column, using standard DAX syntax.


It cannot be an expression.

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
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.
Create a measure named [ResellerSales compared to 2007] using the following expression:

=IF(HASONEVALUE(DateTime[CalendarYear]),SUM(ResellerSales_USD[SalesAmount_USD])/CALCULATE(SUM(ResellerSales_US
D[SalesAmount_USD]),DateTime[CalendarYear]=2007),BLANK())

1. After creating the measure you should have an empty result under [ResellerSales compared to 2007]. 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

3. Drag ProductCategory[ProductCategoryName] to the Row Labels box to have something like this:
RESELLERSALES
COMPARED TO 2007 COLUMN 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 %

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
12/10/2018 • 2 minutes to read

Returns TRUE when columnName or another column in the same or related table is being filtered.

Syntax
ISCROSSFILTERED(<columnName>)

Parameters

TERM DEFINITION

columnName The name of an existing column, using standard DAX syntax.


It cannot be an expression.

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.

See also
ISFILTERED function (DAX)
FILTERS function (DAX)
HASONEFILTER function (DAX)
HASONEVALUE function (DAX)
ISFILTERED
12/10/2018 • 2 minutes to read

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

TERM DEFINITION

columnName The name of an existing column, using standard DAX syntax.


It 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.

See also
ISCROSSFILTERED function (DAX)
FILTERS function (DAX)
HASONEFILTER function (DAX)
HASONEVALUE function (DAX)
KEEPFILTERS
12/10/2018 • 3 minutes to read

Modifies how filters are applied while evaluating a CALCULATE or CALCULATETABLE function.

Syntax
KEEPFILTERS(<expression>)

Parameters

TERM DEFINITION

expression Any expression.

Return value
A table of values.

Remarks
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
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.

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"
|| '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"
)
)

When this expression is evaluated against the sample database AdventureWorks DW Tabular 2012, the following
results are obtained.

COLUMN VALUE

[$$ in WA] $ 2,467,248.34

[$$ in WA and OR] $ 3,638,239.88

[$$ in WA and BC] $ 4,422,588.44

[$$ in WA and OR ??] $ 3,638,239.88

[$$ in WA !!] $ 2,467,248.34

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 functions (DAX)
CALCULATE function (DAX)
CALCULATETABLE function (DAX)
RELATED
12/10/2018 • 2 minutes to read

Returns a related value from another table.

Syntax
RELATED(<column>)

Parameters

TERM DEFINITION

column The column that contains the values you want to retrieve.

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.
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
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)

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.

= SUMX(FILTER( 'InternetSales_USD'
, RELATED('SalesTerritory'[SalesTerritoryCountry])
<>"United States"
)
,'InternetSales_USD'[SalesAmount_USD])

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.

ROW LABELS INTERNET SALES NON USA INTERNET SALES

Australia $4,999,021.84 $4,999,021.84

Canada $1,343,109.10 $1,343,109.10

France $2,490,944.57 $2,490,944.57

Germany $2,775,195.60 $2,775,195.60

United Kingdom $5,057,076.55 $5,057,076.55

United States $9,389,479.79

Grand Total $26,054,827.45 $16,665,347.67

The following table shows the final report that you might get if you used this measure in a PivotTable:

NON USA INTERNET


SALES COLUMN LABELS

Row Labels Accessories Bikes Clothing Grand Total

2005 $1,526,481.95 $1,526,481.95

2006 $3,554,744.04 $3,554,744.04

2007 $156,480.18 $5,640,106.05 $70,142.77 $5,866,729.00


NON USA INTERNET
SALES COLUMN LABELS

2008 $228,159.45 $5,386,558.19 $102,675.04 $5,717,392.68

Grand Total $384,639.63 $16,107,890.23 $172,817.81 $16,665,347.67

See also
RELATEDTABLE function (DAX)
Filter functions (DAX)
RELATEDTABLE
12/10/2018 • 2 minutes to read

Evaluates a table expression in a context modified by the given filters.

Syntax
RELATEDTABLE(<tableName>)

Parameters

TERM DEFINITION

tableName The name of an existing table using standard DAX syntax. It


cannot be an expression.

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.

Example
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.

Product Category Key Product Category Product Category Name Internet Sales
AlternateKey

1 1 Bikes $28,318,144.65

2 2 Components

3 3 Clothing $339,772.61

4 4 Accessories $700,759.96

= SUMX( RELATEDTABLE('InternetSales_USD')
, [SalesAmount_USD])
See also
CALCULATETABLE function (DAX)
Filter functions (DAX)
SELECTEDVALUE
12/10/2018 • 2 minutes to read

Returns the value when the context for columnName has been filtered down to one distinct value only. Otherwise
returns alternateResult.

Syntax
SELECTEDVALUE(<columnName>[, <alternateResult>])

Parameters

TERM DEFINITION

columnName The name of an existing column, using standard DAX syntax. It


cannot be an expression.

alternateResult (Optional) The value returned when the context for


columnName has been filtered down to zero or more than
one distinct value. When not provided, the default value is
BLANK().

Return value
The value when the context for columnName has been filtered down to one distinct value only. Else,
alternateResult.

Remarks
An equivalent expression for SELECTEDVALUE(<columnName>, <alternateResult>) is
IF(HASONEVALUE(<columnName>), VALUES(<columnName>), <alternateResult>) .

Example
The following DAX query:

DEFINE MEASURE DimProduct[Selected Color] = SELECTEDVALUE(DimProduct[Color], "No Single Selection")


EVALUATE SUMMARIZECOLUMNS(ROLLUPADDISSUBTOTAL(DimProduct[Color], "Is Total"), "Selected Color", [Selected
Color])
ORDER BY [Is Total] ASC, [Color] ASC

Returns the following:

DIMPRODUCT[COLOR] [IS TOTAL] [SELECTED COLOR]

Black FALSE Black

Blue FALSE Blue


DIMPRODUCT[COLOR] [IS TOTAL] [SELECTED COLOR]

Grey FALSE Grey

Multi FALSE Multi

NA FALSE NA

Red FALSE Red

Silver FALSE Silver

Silver/Black FALSE Silver/Black

White FALSE White

Yellow FALSE Yellow

TRUE No Single Selection


SUBSTITUTEWITHINDEX
12/10/2018 • 2 minutes to read

Returns a table which represents a left semijoin of the two tables supplied as arguments. The semijoin is
performed by using common columns, determined by common column names and common data type . The
columns being joined on are replaced with a single column in the returned table which is of type integer and
contains an index. The index is a reference into the right join table given a specified sort order.
Columns in the right/second table supplied which do not exist in the left/first table supplied are not included in the
returned table and are not used to join on.
The index starts at 0 (0-based) and is incremented by one for each additional row in the right/second join table
supplied. The index is based on the sort order specified for the right/second join table.

Syntax
SUBSTITUTEWITHINDEX(<table>, <indexColumnName>, <indexColumnsTable>, [<orderBy_expression>, [<order>][,
<orderBy_expression>, [<order>]]…])

Parameters

TERM DEFINITION

table A table to be filtered by performing a left semijoin with the


table specified as the third argument (indexColumnsTable).
This is the table on the left side of the left semijoin so the
table returned includes the same columns as this table except
that all common columns of the two tables will be replaced
with a single index column in the table returned.

indexColumnName A string which specifies the name of the index column which is
replacing all the common columns in the two tables supplied
as arguments to this function.

indexColumnsTable The second table for the left semijoin. This is the table on the
right side of the left semijoin. Only values present in this table
will be returned by the function. Also, the columns of this
table (based on column names) will be replaced with a single
index column in the table returned by this function.

orderBy_expression Any DAX expression where the result value is used to specify
the desired sort order of the indexColumnsTable table for
generating correct index values. The sort order specified for
the indexColumnsTable table defines the index of each row in
the table and that index is used in the table returned to
represent combinations of values in the indexColumnsTable as
they appear in the table supplied as the first argument to this
function.
TERM DEFINITION

order (Optional) A value that specifies how to sort


orderBy_expression values, ascending or descending:

Value: Desc. Alternative value: 0(zero)/FALSE. Sorts in


descending order of values of orderBy_expression. This is the
default value when order parameter is omitted.

Value: ASC. Alternative value: 1/TRUE. Ranks in ascending


order of orderBy_expression.

Return value
A table which includes only those values present in the indexColumnsTable table and which has an index column
instead of all columns present (by name) in the indexColumnsTable table.

Remarks
This function does not guarantee any result sort order.
USERELATIONSHIP
12/10/2018 • 2 minutes to read

Specifies the relationship to be used in a specific calculation as the one that exists between columnName1 and
columnName2.

Syntax
USERELATIONSHIP(<columnName1>,<columnName2>)

Parameters

TERM DEFINITION

columnName1 The name of an existing column, using standard DAX syntax


and fully qualified, that usually represents the many side of
the relationship to be used; if the arguments are given in
reverse order the function will swap them before using them.
This argument cannot be an expression.

columnName2 The name of an existing column, using standard DAX syntax


and fully qualified, that usually represents the one side or
lookup side of the relationship to be used; if the arguments
are given in reverse 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
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.
USERELATIONSHIP cannot be used when row level security is defined for the table in which the measure
is included. For example,
CALCULATE(SUM([SalesAmount]), USERELATIONSHIP(FactInternetSales[CustomerKey], DimCustomer[CustomerKey]))
will return an error if row level security is defined for DimCustomer.
USERELATIONSHIP uses existing relationships in the model, identifying relationships by their ending point
columns.
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.
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.
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.
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.
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( &lt;anyExpression&gt;, USERELATIONSHIP( t1[colA], t2[colB])),
t99[colZ]=999), USERELATIONSHIP( t1[colA], t2[colA]))
.

Example
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:

=CALCULATE(SUM(InternetSales[SalesAmount]), USERELATIONSHIP(InternetSales[ShippingDate], DateTime[Date]))

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
12/10/2018 • 2 minutes to read

Returns a one-column table that contains the distinct values from the specified table or 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(<TableNameOrColumnName>)

Parameters

TERM DEFINITION

TableName or ColumnName The table or column from which unique values are 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, when the argument is a column name, 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 a blank value. This blank 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
occur when one table is being updated and the related table is not.
When the argument is a table name, the result of the VALUES function returns all rows in the specified table plus
a blank row, if there is a violation of referential integrity. The DISTINCT function removes duplicate rows and
returns unique rows in the specified table.
NOTE
The DISTINCT function allows a column name or any valid table expression to be its argument but the VALUES function only
accepts a column name or a table name as the argument.

The following table summarizes the mismatch between data that can occur in two related tables when referential
integrity is not preserved.

MYORDERS TABLE MYSALES TABLE

June 1 June 1 sales

June 2 June 2 sales

(no order dates have been entered) June 3 sales

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
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:

ROW LABELS COUNT INVOICES

Accessories 18,208

Bikes 15,205

Clothing 7,461

Grand Total 27,659

=COUNTROWS(VALUES('InternetSales_USD'[SalesOrderNumber]))

See also
FILTER function (DAX)
COUNTROWS function (DAX)
Filter functions (DAX)
Information functions
12/10/2018 • 2 minutes to read

DAX information functions look 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
CUSTOMDATA
ISBLANK
ISERROR
ISEVEN
ISINSCOPE
ISLOGICAL
ISNONTEXT
ISNUMBER
ISONORAFTER
ISTEXT
LOOKUPVALUE
USERNAME
CONTAINS
12/10/2018 • 2 minutes to read

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

TERM DEFINITION

table Any DAX expression that returns a table of data.

columnName The name of an existing column, using standard DAX syntax. It


cannot be an expression.

value Any DAX expression that returns a single scalar value, that is
to be sought in columnName. The expression is to be
evaluated exactly once and before it is passed to the
argument list.

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
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.

=CONTAINS(InternetSales, [ProductKey], 214, [CustomerKey], 11185)


CUSTOMDATA
12/10/2018 • 2 minutes to read

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
The following DAX code verifies if the CustomData property was set to "OK".

=IF(CUSTOMDATA()="OK", "Correct Custom data in connection string", "No custom data in connection string
property or unexpected value")
IN Operator / CONTAINSROW function
12/10/2018 • 2 minutes to read

Returns TRUE if a row of values exists or contained in a table, otherwise returns FALSE. Except syntax, the IN
operator and CONTAINSROW function are functionally equivalent.

IN Operator
Syntax

<scalarExpr> IN <tableExpr>
( <scalarExpr1>, <scalarExpr2>, … ) IN <tableExpr>

CONTAINSROW function
Syntax

CONTAINSROW(<tableExpr>, <scalarExpr>[, <scalarExpr>, …])

Parameters
TERM DEFINITION

scalarExprN Any valid DAX expression that returns a scalar value.

tableExpr Any valid DAX expression that returns a table of data.

Return value
TRUE or FALSE.

Remarks
The number of scalarExprN must match the number of columns in tableExpr.
Unlike the = operator, the IN operator and the CONTAINSROW function perform strict comparison. For example,
the BLANK value does not match 0.
NOT IN is not an operator in DAX. To perform the logical negation of the IN operator, put NOT in front of the
entire expression. For example, NOT [Color] IN { "Red", "Yellow", "Blue" }.

Examples
Example 1
The following equivalent DAX queries:

EVALUATE FILTER(ALL(DimProduct[Color]), [Color] IN { "Red", "Yellow", "Blue" })


ORDER BY [Color]
and

EVALUATE FILTER(ALL(DimProduct[Color]), ([Color]) IN { "Red", "Yellow", "Blue" })


ORDER BY [Color]

and

EVALUATE FILTER(ALL(DimProduct[Color]), CONTAINSROW({ "Red", "Yellow", "Blue" }, [Color]))


ORDER BY [Color]

Return the following table with a single column:

DIMPRODUCT[COLOR]

Blue

Red

Yellow

Example 2
The following equivalent DAX queries:

EVALUATE FILTER(SUMMARIZE(DimProduct, [Color], [Size]), ([Color], [Size]) IN { ("Black", "L") })

and

EVALUATE FILTER(SUMMARIZE(DimProduct, [Color], [Size]), CONTAINSROW({ ("Black", "L") }, [Color], [Size]))

Return:

DIMPRODUCT[COLOR] DIMPRODUCT[SIZE]

Black L

Example 3
The following equivalent DAX queries:

EVALUATE FILTER(ALL(DimProduct[Color]), NOT [Color] IN { "Red", "Yellow", "Blue" })


ORDER BY [Color]

and

EVALUATE FILTER(ALL(DimProduct[Color]), NOT CONTAINSROW({ "Red", "Yellow", "Blue" }, [Color]))


ORDER BY [Color]

Return the following table with a single column:


DIMPRODUCT[COLOR]

Black

Grey

Multi

NA

Silver

Silver\Black

White
ISBLANK
12/10/2018 • 2 minutes to read

Checks whether a value is blank, and returns TRUE or FALSE.

Syntax
ISBLANK(<value>)

Parameters

TERM DEFINITION

value The value or expression you want to test.

Return value
A Boolean value of TRUE if the value is blank; otherwise FALSE.

Example
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.

SALES TO PREVIOUS YEAR


ROW LABELS TOTAL SALES TOTAL SALES 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

//Sales to Previous Year Ratio

=IF( ISBLANK('CalculatedMeasures'[PreviousYearTotalSales])
, BLANK()
, ( 'CalculatedMeasures'[Total Sales]-'CalculatedMeasures'[PreviousYearTotalSales] )
/'CalculatedMeasures'[PreviousYearTotalSales])

See also
Information functions (DAX)
ISERROR
12/10/2018 • 2 minutes to read

Checks whether a value is an error, and returns TRUE or FALSE.

Syntax
ISERROR(<value>)

Parameters

TERM DEFINITION

value The value you want to test.

Return value
A Boolean value of TRUE if the value is an error; otherwise FALSE.

Example
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.

= 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 function (DAX)
IF function (DAX)
ISEVEN
12/10/2018 • 2 minutes to read

Returns TRUE if number is even, or FALSE if number is odd.

Syntax
ISEVEN(number)

Parameters

TERM DEFINITION

number The value to test. If number is not an integer, it is truncated.

Return value
Returns TRUE if number is even, or FALSE if number is odd.

Remarks
If number is nonnumeric, ISEVEN returns the #VALUE! error value.
ISINSCOPE
12/10/2018 • 2 minutes to read

Returns true when the specified column is the level in a hierarchy of levels.

Syntax
ISINSCOPE(<columnName>)

Parameters

TERM DEFINITION

columnName The name of an existing column, using standard DAX syntax.


It cannot be an expression.

Return value
TRUE when the specified column is the level in a hierarchy of levels.

Example
DEFINE
MEASURE FactInternetSales[% of Parent] =
SWITCH (TRUE(),
ISINSCOPE(DimProduct[Subcategory]),
DIVIDE(
SUM(FactInternetSales[Sales Amount]),
CALCULATE(
SUM(FactInternetSales[Sales Amount]),
ALLSELECTED(DimProduct[Subcategory]))
),
ISINSCOPE(DimProduct[Category]),
DIVIDE(
SUM(FactInternetSales[Sales Amount]),
CALCULATE(
SUM(FactInternetSales[Sales Amount]),
ALLSELECTED(DimProduct[Category]))
),
1
) * 100
EVALUATE
SUMMARIZECOLUMNS
(
ROLLUPADDISSUBTOTAL
(
DimProduct[Category], "Category Subtotal",
DimProduct[Subcategory], "Subcategory Subtotal"
),
TREATAS(
{"Bike Racks", "Bike Stands", "Mountain Bikes", "Road Bikes", "Touring Bikes"},
DimProduct[Subcategory]),
"Sales", SUM(FactInternetSales[Sales Amount]),
"% of Parent", [% of Parent]
)
ORDER BY
[Category Subtotal] DESC, [Category],
[Subcategory Subtotal] DESC, [Subcategory]

Returns

DIMPRODUCT[CAT DIMPRODUCT[SUB [CATEGORY [SUBCATEGORY


EGORY] CATEGORY] SUBTOTAL] SUBTOTAL] [SALES] [% OF PARENT]

TRUE TRUE 28,397,095.65 100.00

Accessories FALSE TRUE 78,951.00 0.28

Accessories Bike Racks FALSE FALSE 39,360.00 49.85

Accessories Bike Stands FALSE FALSE 39,591.00 50.15

Bikes FALSE TRUE 28,318,144.65 99.72

Bikes Mountain Bikes FALSE FALSE 9,952,759.56 35.15

Bikes Road Bikes FALSE FALSE 14,520,584.04 51.28

Bikes Touring Bikes FALSE FALSE 3,844,801.05 13.58

See also
SUMMARIZECOLUMNS function (DAX)
CALCULATE function (DAX)
ISLOGICAL
12/10/2018 • 2 minutes to read

Checks whether a value is a logical value, (TRUE or FALSE ), and returns TRUE or FALSE.

Syntax
ISLOGICAL(<value>)

Parameters

TERM DEFINITION

value The value that you want to test.

Property Value/Return value


TRUE if the value is a logical value; FALSE if any value other than TRUE OR FALSE.

Example
The following three samples show the behavior of ISLOGICAL.

//RETURNS: Is Boolean type or Logical


=IF(ISLOGICAL(true), "Is Boolean type or Logical", "Is different type")

//RETURNS: Is Boolean type or Logical


=IF(ISLOGICAL(false), "Is Boolean type or Logical", "Is different type")

//RETURNS: Is different type


=IF(ISLOGICAL(25), "Is Boolean type or Logical", "Is different type")

See also
Information functions (DAX)
ISNONTEXT
12/10/2018 • 2 minutes to read

Checks if a value is not text (blank cells are not text), and returns TRUE or FALSE.

Syntax
ISNONTEXT(<value>)

Parameters

TERM DEFINITION

value The value you want to check.

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
The following examples show the behavior of the ISNONTEXT function.

//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
12/10/2018 • 2 minutes to read

Checks whether a value is a number, and returns TRUE or FALSE.

Syntax
ISNUMBER(<value>)

Parameters

TERM DEFINITION

value The value you want to test.

Property Value/Return value


TRUE if the value is numeric; otherwise FALSE.

Example
The following three samples show the behavior of ISNUMBER.

//RETURNS: Is number
=IF(ISNUMBER(0), "Is number", "Is Not number")

//RETURNS: Is number
=IF(ISNUMBER(3.1E-1),"Is number", "Is Not number")

//RETURNS: Is Not number


=IF(ISNUMBER("123"), "Is number", "Is Not number")

See also
Information functions (DAX)
ISODD
12/10/2018 • 2 minutes to read

Returns TRUE if number is odd, or FALSE if number is even.

Syntax
ISODD(number)

Parameters

TERM DEFINITION

number The value to test. If number is not an integer, it is truncated.

Return value
Returns TRUE if number is odd, or FALSE if number is even.

Remarks
If number is nonnumeric, ISODD returns the #VALUE! error value.
ISONORAFTER
1/16/2019 • 2 minutes to read

A boolean function that emulates the behavior of a ‘Start At’ clause and returns true for a row that meets all of the
condition parameters.
This function takes a variable number of triples, the first two values in a triple are the expressions to be compared,
and the third parameter indicates the sort order. The sort order can be ascending (default) or descending.
Based on the sort order, the first parameter is compared with the second parameter. If the sort order is ascending,
the comparison to be done is first parameter greater than or equal to second parameter. If the sort order is
descending, the comparison to be done is second parameter less than or equal to first parameter.

Syntax
ISONORAFTER(<scalar_expression>, <scalar_expression>[, sort_order [, <scalar_expression>, <scalar_expression>
[, sort_order]]…)

Parameters

TERM DEFINITION

scalar expression Any expression that returns a scalar value like a column
reference or integer or string value. Typically the first
parameter is a column reference and the second parameter is
a scalar value.

sort order (optional) The order in which the column is sorted. Can be
ascending (ASC) or descending (DEC). By default the sort
order is ascending.

Return value
True or false.

Example
Table name: ‘Info’

COUNTRY STATE COUNT TOTAL

IND JK 20 800

IND` MH 25 1000

IND WB 10 900

USA CA 5 500

USA WA 10 900
FILTER(Info, ISONORAFTER(Info[Country], “IND”, ASC, Info[State], “MH”, ASC))
ISTEXT
12/10/2018 • 2 minutes to read

Checks if a value is text, and returns TRUE or FALSE.

Syntax
ISTEXT(<value>)

Parameters

TERM DEFINITION

value The value you want to check.

Property Value/Return value


TRUE if the value is text; otherwise FALSE

Example
The following examples show the behavior of the ISTEXT function.

//RETURNS: Is Text
=IF(ISTEXT("text"), "Is Text", "Is Non-Text")

//RETURNS: Is Text
=IF(ISTEXT(""), "Is Text", "Is Non-Text")

//RETURNS: Is Non-Text
=IF(ISTEXT(1), "Is Text", "Is Non-Text")

//RETURNS: Is Non-Text
=IF(ISTEXT(BLANK()), "Is Text", "Is Non-Text")

See also
Information functions (DAX)
LOOKUPVALUE
12/10/2018 • 2 minutes to read

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

TERM DEFINITION

result_columnName The name of an existing column that contains the value you
want to return. The column must be named using standard
DAX syntax, usually, fully qualified. It cannot be an expression.

search_columnName The name of an existing column, in the same table as


result_columnName or in a related table, over which the look-
up is performed. The column must be named using standard
DAX syntax, usually, fully qualified. It cannot be an expression.

search_value A scalar expression that does not refer to any column in the
same table being searched.

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.
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
The following example returns the SafetyStocklLevel for the bike model "Mountain-400-W Silver, 46".

=LOOKUPVALUE(Product[SafetyStockLevel], [ProductName], " Mountain-400-W Silver, 46")


USERNAME
12/10/2018 • 2 minutes to read

Returns the domain name and username from the credentials given to the system at connection time

Syntax
USERNAME()

Parameters

Return value
The username from the credentials given to the system at connection time

Example
The following code verifies if the user login is part of the UsersTable.

=IF(CONTAINS(UsersTable,UsersTable[login], USERNAME()), "Allowed", BLANK())


Logical functions
12/10/2018 • 2 minutes to read

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
FALSE
IF
IFERROR
NOT
OR
SWITCH
TRUE
AND
12/10/2018 • 2 minutes to read

Checks whether both arguments are TRUE, and returns TRUE if both arguments are TRUE. Otherwise returns
false.

Syntax
AND(<logical1>,<logical2>)

Parameters

TERM DEFINITION

logical_1, logical_2 The logical values you want to test.

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
The following formula shows the syntax of the AND function.

=IF(AND(10 > 9, -10 < -1), "All true", "One or more false"

Because both conditions, passed as arguments, to the AND function are true, the formula returns "All True".

Example
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 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".

COLUMN
AND FUNCTION LABELS

Row Labels 2005 2006 2007 2008 Grand Total

Bib-Shorts
COLUMN
AND FUNCTION LABELS

Bike Racks

Bike Stands Internet Hit

Bottles and Internet Hit


Cages

Bottom
Brackets

Brakes

Caps

Chains

Cleaners

Cranksets

Derailleurs

Fenders Internet Hit

Forks

Gloves

Handlebars

Headsets

Helmets

Hydration
Packs

Jerseys

Lights

Locks

Mountain
Bikes

Mountain
Frames

Panniers
COLUMN
AND FUNCTION LABELS

Pedals

Pumps

Road Bikes

Road Frames

Saddles

Shorts

Socks

Tights

Tires and Internet Hit


Tubes

Touring Bikes

Touring
Frames

Vests

Wheels

Grand Total

= 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] ))
)
, "Internet Hit"
, ""
)

See also
Logical functions (DAX)
FALSE
12/10/2018 • 2 minutes to read

Returns the logical value FALSE.

Syntax
FALSE()

Return value
Always FALSE.

Remarks
The word FALSE is also interpreted as the logical value FALSE.

Example
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.

COLUMN
TRUE-FALSE LABELS

Row Labels 2005 2006 2007 2008 Grand Total

Accessories FALSE FALSE TRUE TRUE FALSE TRUE

Bikes TRUE TRUE TRUE TRUE FALSE TRUE

Clothing FALSE FALSE FALSE FALSE FALSE TRUE

Components FALSE FALSE FALSE FALSE FALSE FALSE

FALSE FALSE FALSE FALSE FALSE FALSE

Grand Total TRUE TRUE TRUE TRUE FALSE TRUE

=IF(SUM('InternetSales_USD'[SalesAmount_USD]) >200000, TRUE(), false())

See also
TRUE function (DAX)
NOT function (DAX)
IF function (DAX)
DAX function reference
IF
12/10/2018 • 2 minutes to read

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

logical_test Any value or expression that can be evaluated to TRUE or


FALSE.

value_if_true The value that is returned if the logical test is TRUE. If


omitted, TRUE is returned.

value_if_false The value that is returned if the logical test is FALSE. If


omitted, FALSE is returned.

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 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 Supported (SSAS
Tabular).

Example
The following example uses nested IF functions that evaluate the number in the column, Calls, from the table
FactCallCenter. 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.

=IF([Calls]<200,"low",IF([Calls]<300,"medium","high"))

Example
The following example gets a list of cities that contain potential customers in the California area by using columns
from the table ProspectiveBuyer. 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.

=IF([StateProvinceCode]= "CA" && ([MaritalStatus] = "M" || [NumberChildrenAtHome] >1),[City])

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 function (DAX)
FALSE function (DAX)
NOT function (DAX)
IF function (DAX)
DAX function reference
IFERROR
12/10/2018 • 2 minutes to read

Evaluates an expression and returns a specified value if the expression returns an error; otherwise returns the
value of the expression itself.

Syntax
IFERROR(value, value_if_error)

Parameters

TERM DEFINITION

value Any value or expression.

value_if_error Any value or expression.

Return value
A scalar of the same type as value

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
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.

=IFERROR(25/0,9999)

See also
Logical functions (DAX)
IN
12/10/2018 • 2 minutes to read

Returns True if the scalar value shows up in at least one row of the input relation.

Syntax
IN

Parameters

TERM DEFINITION

scalar expression

table expression

Return value
Remarks
Example
Filtered Sales:=CALCULATE (
[Internet Total Sales], 'Product'[Color] IN { "Red", "Blue", "Black" }
)

See also
NOT
12/10/2018 • 2 minutes to read

Changes FALSE to TRUE, or TRUE to FALSE.

Syntax
NOT(<logical>)

Parameters

TERM DEFINITION

logical A value or expression that can be evaluated to TRUE or FALSE.

Return value
TRUE OR FALSE.

Example
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.

=NOT([CalculatedColumn1])

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 function (DAX)
FALSE function (DAX)
IF function (DAX)
DAX function reference
OR
12/10/2018 • 2 minutes to read

Checks whether one of the arguments is TRUE to return TRUE. The function returns FALSE if both arguments are
FALSE.

Syntax
OR(<logical1>,<logical2>)

Parameters

TERM DEFINITION

logical_1, logical_2 The logical values you want to test.

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
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.

SALESPERSONF
LAG TRUE

OR function Column
Labels

Row Labels 2005 2006 2007 2008 Grand Total

Abbas, Syed E

Alberts, Amy E
SALESPERSONF
LAG TRUE

Ansman-
Wolfe, Pamela
O

Blythe, Circle of Circle of Circle of Circle of Circle of Circle of


Michael G Excellence Excellence Excellence Excellence Excellence Excellence

Campbell,
David R

Carson, Jillian Circle of Circle of Circle of Circle of Circle of Circle of


Excellence Excellence Excellence Excellence Excellence Excellence

Ito, Shu K

Jiang, Stephen
Y

Mensa-
Annan, Tete A

Mitchell, Linda Circle of Circle of Circle of Circle of Circle of Circle of


C Excellence Excellence Excellence Excellence Excellence Excellence

Pak, Jae B Circle of Circle of Circle of Circle of Circle of Circle of


Excellence Excellence Excellence Excellence Excellence Excellence

Reiter, Tsvi
Michael

Saraiva, José Circle of Circle of Circle of Circle of Circle of Circle of


Edvaldo Excellence Excellence Excellence Excellence Excellence Excellence

Tsoflias, Lynn
N

Valdez, Rachel
B

Vargas,
Garrett R

Varkey Circle of
Chudukatil, Excellence
Ranjit R

Grand Total Circle of Circle of Circle of Circle of Circle of Circle of


Excellence Excellence Excellence Excellence Excellence Excellence
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"
, ""
)

See also
Logical functions (DAX)
SWITCH
12/10/2018 • 2 minutes to read

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

TERM DEFINITION

expression Any DAX expression that returns a single scalar value, where
the expression is to be evaluated multiple times (for each
row/context).

value A constant value to be matched with the results of expression.

result Any scalar expression to be evaluated if the results of


expression match the corresponding value.

else Any scalar expression to be evaluated if the result of


expression doesn't match any of the value arguments.

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.

Remarks
All result expressions and the else expression must be of the same data type.

Example
The following example creates a calculated column of month names.

=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" )
TRUE
12/10/2018 • 2 minutes to read

Returns the logical value TRUE.

Syntax
TRUE()

Return value
Always TRUE.

Remarks
The word TRUE is also interpreted as the logical value TRUE.

Example
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.

COLUMN
TRUE-FALSE LABELS

Row Labels 2005 2006 2007 2008 Grand Total

Accessories FALSE FALSE TRUE TRUE FALSE TRUE

Bikes TRUE TRUE TRUE TRUE FALSE TRUE

Clothing FALSE FALSE FALSE FALSE FALSE TRUE

Components FALSE FALSE FALSE FALSE FALSE FALSE

FALSE FALSE FALSE FALSE FALSE FALSE

Grand Total TRUE TRUE TRUE TRUE FALSE TRUE

= IF(SUM('InternetSales_USD'[SalesAmount_USD]) >200000, TRUE(), false())

See also
FALSE function (DAX)
NOT function (DAX)
IF function (DAX)
DAX function reference
Math and Trig functions
12/10/2018 • 2 minutes to read

The mathematical functions in Data Analysis Expressions (DAX) are very similar to the Excel mathematical and
trigonometric functions. This section lists the mathematical functions provided by DAX.

In this section
ABS
ACOS
ACOSH
ASIN
ASINH
ATAN
ATANH
CEILING
COMBIN
COMBINA
COS
COSH
CURRENCY
DEGREES
DIVIDE
EVEN
EXP
FACT
FLOOR
GCD
INT
ISO.CEILING
LCM
LN
LOG
LOG10
INT
MROUND
ODD
PI
POWER
PRODUCT
PRODUCTX
QUOTIENT
RADIANS
RAND
RANDBETWEEN
ROUND
ROUNDDOWN
ROUNDUP
SIGN
SQRT
SUM
SUMX
TRUNC
ABS
12/10/2018 • 2 minutes to read

Returns the absolute value of a number.

Syntax
ABS(<number>)

Parameters

TERM DEFINITION

number The number for which you want the absolute value.

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
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.

=ABS([DealerPrice]-[ListPrice])

See also
Math and Trig functions (DAX)
SIGN function (DAX)
ACOS
12/10/2018 • 2 minutes to read

Returns the arccosine, or inverse cosine, of a number. The arccosine is the angle whose cosine is number. The
returned angle is given in radians in the range 0 (zero) to pi.

Syntax
ACOS(number)

Parameters

TERM DEFINITION

Number The cosine of the angle you want and must be from -1 to 1.

Return value
Returns the arccosine, or inverse cosine, of a number.

Remarks
If you want to convert the result from radians to degrees, multiply it by 180/PI() or use the DEGREES function.

Example
FORMULA DESCRIPTION RESULT

=ACOS(-0.5) Arccosine of -0.5 in radians, 2*pi/3. 2.094395102

=ACOS(-0.5)*180/PI() Arccosine of -0.5 in degrees. 120


ACOSH
12/10/2018 • 2 minutes to read

Returns the inverse hyperbolic cosine of a number. The number must be greater than or equal to 1. The inverse
hyperbolic cosine is the value whose hyperbolic cosine is number, so ACOSH(COSH(number)) equals number.

Syntax
ACOSH(number)

Parameters

TERM DEFINITION

number Any real number equal to or greater than 1.

Return value
Returns the inverse hyperbolic cosine of a number.

Example
FORMULA DESCRIPTION RESULT

=ACOSH(1) Inverse hyperbolic cosine of 1. 0

=ACOSH(10) Inverse hyperbolic cosine of 10. 2.993228


ASIN
12/10/2018 • 2 minutes to read

Returns the arcsine, or inverse sine, of a number. The arcsine is the angle whose sine is number. The returned angle
is given in radians in the range -pi/2 to pi/2.

Syntax
ASIN(number)

Parameters

TERM DEFINITION

number The sine of the angle you want and must be from -1 to 1.

Return value
Returns the arcsine, or inverse sine, of a number.

Remarks
To express the arcsine in degrees, multiply the result by 180/PI( ) or use the DEGREES function.

Example
FORMULA DESCRIPTION RESULT

=ASIN(-0.5) Arcsine of -0.5 in radians, -pi/6 -0.523598776

=ASIN(-0.5)*180/PI() Arcsine of -0.5 in degrees -30

=DEGREES(ASIN(-0.5)) Arcsine of -0.5 in degrees -30


ASINH
12/10/2018 • 2 minutes to read

Returns the inverse hyperbolic sine of a number. The inverse hyperbolic sine is the value whose hyperbolic sine is
number, so ASINH(SINH(number)) equals number.

Syntax
ASINH(number)

Parameters

TERM DEFINITION

number Any real number.

Return value
Returns the inverse hyperbolic sine of a number.

Example
FORMULA DESCRIPTION RESULT

=ASINH(-2.5) Inverse hyperbolic sine of -2.5 -1.647231146

=ASINH(10) Inverse hyperbolic sine of 10 2.99822295


ATAN
12/10/2018 • 2 minutes to read

Returns the arctangent, or inverse tangent, of a number. The arctangent is the angle whose tangent is number. The
returned angle is given in radians in the range -pi/2 to pi/2.

Syntax
ATAN(number)

Parameters

TERM DEFINITION

number The tangent of the angle you want.

Return value
Returns the inverse hyperbolic tangent of a number.

Remarks
To express the arctangent in degrees, multiply the result by 180/PI( ) or use the DEGREES function.

Example
FORMULA DESCRIPTION RESULT

=ATAN(1) Arctangent of 1 in radians, pi/4 0.785398163

=ATAN(1)*180/PI() Arctangent of 1 in degrees 45


ATANH
12/10/2018 • 2 minutes to read

Returns the inverse hyperbolic tangent of a number. Number must be between -1 and 1 (excluding -1 and 1). The
inverse hyperbolic tangent is the value whose hyperbolic tangent is number, so ATANH(TANH(number)) equals
number.

Syntax
ATANH(number)

Parameters

TERM DEFINITION

number Any real number between 1 and -1.

Return value
Returns the inverse hyperbolic tangent of a number.

Example
FORMULA DESCRIPTION RESULT

=ATANH(0.76159416) Inverse hyperbolic tangent of 1.00000001


0.76159416

=ATANH(-0.1) -0.100335348

See also
ATAN function (DAX)
CEILING
12/10/2018 • 2 minutes to read

Rounds a number up, to the nearest integer or to the nearest multiple of significance.

Syntax
CEILING(<number>, <significance>)

Parameters

TERM DEFINITION

number The number you want to round, or a reference to a column


that contains numbers.

significance The multiple of significance to which you want to round. For


example, to round to the nearest integer, type 1.

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
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.

=CEILING(4.42,0.05)
Example
The following formula returns similar results as the previous example, but uses numeric values stored in the
column, ProductPrice.

=CEILING([ProductPrice],0.05)

See also
Math and Trig functions (DAX)
FLOOR function (DAX)
ISO.CEILING function (DAX)
ROUNDUP function (DAX)
COMBIN
12/10/2018 • 2 minutes to read

Returns the number of combinations for a given number of items. Use COMBIN to determine the total possible
number of groups for a given number of items.

Syntax
COMBIN(number, number_chosen)

Parameters

TERM DEFINITION

number The number of items.

number_chosen The number of items in each combination.

Return value
Returns the number of combinations for a given number of items.

Remarks
Numeric arguments are truncated to integers.
If either argument is nonnumeric, COMBIN returns the #VALUE! error value.
If number < 0, number_chosen < 0, or number < number_chosen, COMBIN returns the #NUM! error value.
A combination is any set or subset of items, regardless of their internal order. Combinations are distinct from
permutations, for which the internal order is significant.
The number of combinations is as follows, where number = n and number_chosen = k:

Where

Example
FORMULA DESCRIPTION RESULT

=COMBIN(8,2) Possible two-person teams that can be 28


formed from 8 candidates.
COMBINA
12/10/2018 • 2 minutes to read

Returns the number of combinations (with repetitions) for a given number of items.

Syntax
COMBINA(number, number_chosen)

Parameters

TERM DEFINITION

number Must be greater than or equal to 0, and greater than or equal


to Number_chosen. Non-integer values are truncated.

number_chosen Must be greater than or equal to 0. Non-integer values are


truncated.

Return value
Returns the number of combinations (with repetitions) for a given number of items.

Remarks
If the value of either argument is outside of its constraints, COMBINA returns the #NUM! error value.
If either argument is a non-numeric value, COMBINA returns the #VALUE! error value.
The following equation is used, where N is Number and M is Number_chosen:

Example
FORMULA DESCRIPTION RESULT

=COMBINA(4,3) Returns the number of combinations 20


(with repetitions) for 4 and 3.

=COMBINA(10,3) Returns the number of combinations 220


(with repetitions) for 10 and 3.
COS
12/10/2018 • 2 minutes to read

Returns the cosine of the given angle.

Syntax
COS(number)

Parameters

TERM DEFINITION

number Required. The angle in radians for which you want the cosine.

Return value
Returns the cosine of the given angle.

Remarks
If the angle is in degrees, either multiply the angle by PI()/180 or use the RADIANS function to convert the angle
to radians.

Example
FORMULA DESCRIPTION RESULT

=COS(1.047) Cosine of 1.047 radians 0.5001711

=COS(60*PI()/180) Cosine of 60 degrees 0.5

=COS(RADIANS(60)) Cosine of 60 degrees 0.5


COSH
12/10/2018 • 2 minutes to read

Returns the hyperbolic cosine of a number.

Syntax
COSH(number)

Parameters

TERM DEFINITION

number Required. Any real number for which you want to find the
hyperbolic cosine.

Return value
The hyperbolic cosine of a number.

Remarks
The formula for the hyperbolic cosine is:

Example
FORMULA DESCRIPTION RESULT

=COSH(4) Hyperbolic cosine of 4 27.308233

=COSH(EXP(1)) Hyperbolic cosine of the base of the 7.6101251


natural logarithm.
CURRENCY
12/10/2018 • 2 minutes to read

Evaluates the argument and returns the result as currency data type.

Syntax
CURRENCY(<value>)

Parameters

TERM DEFINITION

value Any DAX expression that returns a single scalar value where
the expression is to be evaluated exactly once before all other
operations.

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.

Example
Convert number 1234.56 to currency data type.

=CURRENCY(1234.56)

Returns the value $1234.5600.


DEGREES
12/10/2018 • 2 minutes to read

Converts radians into degrees.

Syntax
DEGREES(angle)

Parameters

TERM DEFINITION

angle Required. The angle in radians that you want to convert.

Example
FORMULA DESCRIPTION RESULT

=DEGREES(PI()) Degrees of pi radians 180


DIVIDE
12/10/2018 • 2 minutes to read

Performs division and returns alternate result or BLANK() on division by 0.

Syntax
DIVIDE(<numerator>, <denominator> [,<alternateresult>])

Parameters

TERM DEFINITION

numerator The dividend or number to divide.

denominator The divisor or number to divide by.

alternateresult (Optional) The value returned when division by zero results in


an error. When not provided, the default value is BLANK().

Return value
A decimal number.

Remarks
Alternate result on divide by 0 must be a constant.

Example
The following example returns 2.5.

=DIVIDE(5,2)

Example
The following example returns BLANK.

=DIVIDE(5,0)

Example
The following example returns 1.

=DIVIDE(5,0,1)
See also
QUOTIENT function (DAX)
Math and Trig functions (DAX)

You might also like