DAX Zero To Hero
DAX Zero To Hero
Swipe Right
@ramakrushnamohapatra
GrowTechie
1. Language Of BI
● Power BI
● Analytics Service Tabular
● Power Pivot
What Is DAX ?
1. Programming language
• Power BI
• Analysis Services Tabular
• Power Pivot
1. Resembles Excel
• Because it was born with PowerPivot
• Important differences
• No concept of «row» and «column»
• Different type system
1. Many new functions
2. Designed for data models and business
GrowTechie
Functional Language
DAX is a functional language, the execution flows with function calls, here is
an example of a DAX formula.
=SUMX (FILTER (
VALUES ( 'Date'[Year] ),
'Date'[Year] < 2005
),
IF (
'Date'[Year] >= 2000,
[Sales Amount] * 100,
[Sales Amount] * 90
))
GrowTechie
=SUMX (FILTER (
VALUES ( 'Date'[Year] ),
'Date'[Year] < 2005
),
IF ( 'Date'[Year] >= 2000,
[Sales Amount] * 100,
[Sales Amount] * 90
))
GrowTechie
1. Numeric types
2. Other types
• String
• Binary Objects
GrowTechie
1. Operator Overloading
1. Example:
• "4" + "8" = 12
• 4 & 8 = "48"
DateTime
1. Integer part
• Number of days after December, 30, 1899
1. Decimal part
• Seconds: 1 / ( 24 * 60 * 60 )
1. DateTime Expressions
• Date + 1 = The day after
• Date - 1 = The day before
GrowTechie
Calculated Columns
1. Product[Price] means
Column References
1. The general format to reference a column
• 'TableName'[ColumnName]
Measures
1. Written using DAX
1. Examples
• GrossMargin
• is a calculated column
• but can be a measure, too
• GrossMargin %
• must be a measure
GrowTechie
Naming Convention
1. Measures should not belong to a table
• Columns → Table[Column]
• Measures → [Measure]
GrowTechie
1. Use a measure
• Calculate percentages
• Calculate ratios
• Need complex aggregations
Aggregation Functions
1. Useful to aggregate values
• SUM
• AVERAGE
• MIN
• MAX
1. Iterate over the table and evaluate the expression for each
row
Example Of SUMX
For each row in the Sales table, evaluates the formula, then sum up all the results.
Inside the formula, there is a «current row».
GrowTechie
SUM or SUMX?
Actually, SUM is nothing but syntax sugar for SUMX
--
-- This is the compact format for a SUM
--
SUM ( Sales[Quantity] )
--
-- Internally, this is translated into
--
SUMX (
Sales,
Sales[Quantity]
)
GrowTechie
IN Operator
Customer[State] = "WA"
|| Customer[State] = "NY"
|| Customer[State] = "CA"
GrowTechie
IF (
Sales[SalesAmount] <> 0,
Sales[GrossMargin] / Sales[SalesAmount],
0)
DIVIDE (
Sales[GrossMargin],
Sales[SalesAmount],
0)
GrowTechie
Using Variables
Very useful to avoid repeating subexpressions in your code.
VAR
RETURN
IF (
TotalQuantity > 1000,
TotalQuantity * 0.95,
TotalQuantity * 1.25
)
GrowTechie
Relational Functions
1. RELATED
1. RELATEDTABLE
Table Functions
GrowTechie
Table Functions
1. Basic functions that work and/or return full tables
• FILTER
• ALL
• VALUES / DISTINCT
• RELATEDTABLE
• ADDCOLUMNS / SUMMARIZE
Filtering A Table
GrowTechie
1. FILTER
Ignoring Filters
GrowTechie
• ALL ( Customers[CustomerName] )
• The result contains a table with one column
GrowTechie
COUNTROWS (
ALL (
Orders[Channel],
Orders[Color], Columns of the
same table
Orders[Size]
)
)
GrowTechie
Mixing Filters
Mixing Filters
GrowTechie
DISTINCT
Returns the unique values of a column, only the ones visible in the current filter
context.
NumOfProducts :=
COUNTROWS (
DISTINCT ( Product[ProductCode] )
)
GrowTechie
Returns the unique values of a column, only the ones visible in the current filter
context.
VALUES
Returns the unique values of a column, only the ones visible in the current filter
context, including the additional blank row if it is visible in the filter context.
NumOfProducts :=
COUNTROWS (
VALUES ( Product[ProductCode] )
)
GrowTechie
ALLSELECTED
ALLSELECTED returns the elements of a table as they are visible outside of the
current visual, be either a pivot table in Excel or a visual in Power BI.
GrowTechie
RELATEDTABLE
Returns a table with all the rows related with the current one.
NumOfProducts =
COUNTROWS (
RELATEDTABLE ( Product )
)
GrowTechie
ADDCOLUMNS
Adds one or more columns to a table expression, keeping all existing columns.
It is an iterator, therefore you can access columns of the iterated table
ColorsAndSales
ADDCOLUMNS (
SUMX (
RELATEDTABLE ( Sales ),
))
GrowTechie
Sel Category :=
IF (
HASONEVALUE ( 'Product Category'[Category] ),
"Multiple values"
)
GrowTechie
SELECTEDVALUE
SELECTEDVALUE is a convenient function that simplifies retrieving the value of a
column, when only one value is visible.
SELECTEDVALUE (
'Product Category'[Category],
"Multiple values"
)
Equivalent to:
IF (
HASONEVALUE ( 'Product Category'[Category] ),
VALUES ( 'Product Category'[Category] ),
"Multiple values"
)
GrowTechie
Table variables
A variable can contain either a scalar value or a table. Using table variables greatly
helps in splitting complex expressions.
VAR
SalesGreaterThan10 = FILTER ( Sales, Sales[Quantity] > 10 )
RETURN
SUMX (
FILTER (
SalesGreaterThan10,
RELATED ( Product[Color] ) = "Red"
),
Sales[Amount]
)
GrowTechie
Evaluation Contexts
GrowTechie
Evaluation contexts
Filter context
1. Defined by
• Row Selection
• Column Selection
• Report Filters
• Slicers Selection
Row context
1. Defined by
• Calculated column definition
• Defined automatically for each row
• Row Iteration functions
• SUMX, AVERAGEX …
• All «X» functions and iterators
• Defined by the user formulas
Filtering a table
GrowTechie
Ignoring filters
GrowTechie
SUMX (
Sales,
Sales[Quantity]
* RELATED ( Products[ListPrice] )
* RELATED ( Categories[Discount] )
)
SUMX (
Categories,
SUMX (
RELATEDTABLE ( Products ),
SUMX (
RELATEDTABLE ( Sales )
( Sales[Quantity] * Products[ListPrice] )
Three row contexts:
* Categories[Discount] • Categories
) ) ) • Products of category
• Sales of product
GrowTechie
Ranking by price
Products[RankOnPrice] =
VAR CurrentListPrice = Products[ListPrice]
VAR AllPrices = ALL ( Products[ListPrice] )
RETURN
COUNTROWS (
FILTER (
AllPrices,
Products[ListPrice] > CurrentListPrice
)
)+1
GrowTechie
RELATED
RELATED ( table[column] )
• Opens a new row context on the target table
• Following relationships
GrowTechie
RELATEDTABLE
1. RELATEDTABLE ( table )
• Filters the parameter table
• Returns only rows related with the current one
1. It is the companion of RELATED
GrowTechie
Bidirectional cross-filter
CALCULATE
GrowTechie
CALCULATE syntax
Filters are evaluated in the outer filter context, then combined together in AND, and
finally used to build a new filter context into which DAX evaluates the expression.
GrowTechie
CALCULATE examples
Compute the sum of sales where the price is greater than $100.00.
GrowTechie
CALCULATE Examples
GrowTechie
CALCULATE examples
Compute the sales amount for all of the product colors, regardless of the user
selection.
GrowTechie
CALCULATE examples
Compute the sales amount for red products, regardless of user selection for color.
The filter context is applied on the entire model, products filter the Sales table, too.
GrowTechie
CALCULATE examples
Compute the sales amount for red and blue products, within the user selection for color.
GrowTechie
KEEPFILTERS
KEEPFILTERS retains the previous filters, instead of replacing them.
GrowTechie
CALCULATE operators
o In DAX you work by manipulating filters with the following internal operators:
• INTERSECT (multiple filters in CALCULATE)
• OVERWRITE (nested CALCULATE)
• REMOVEFILTERS (using ALL)
• ADDFILTER (using KEEPFILTERS)
GrowTechie
Context transition
GrowTechie
Context transition
Context transition
GrowTechie
O It does not filter one row, it filters all the identical rows
O It transforms all the row contexts, not only the last one
Automatic CALCULATE
Whenever a measure is invoked, an automatic CALCULATE is added around the measure.
This is the reason why using [Measure] and Table[Column] as a standard is a best practice.
SUMX (
Orders,
[Sales Amount]
)
SUMX (
Orders,
CALCULATE ( [Sales Amount] )
)
GrowTechie
MinSalesPerCustomer :=
MINX ( Customer, [Sales Amount] )
MaxSalesPerCustomer :=
MAXX ( Customer, [Sales Amount] )
GrowTechie
Useful iterators
There are many useful iterators, they all behave the same way: iterate on a table, compute
an expression and aggregate its value.
MAXX
MINX
AVERAGEX
SUMX
PRODUCTX
CONCATENATEXVARX.P | .S
STDEVX.P | .S
MEDIANX
PERCENTILEX.EXC | .INC
GEOMEANX
GrowTechie
Useful iterators
There are many useful iterators, they all behave the same way: iterate on a table, compute
an expression and aggregate its value.
MAXX
MINX
AVERAGEX
SUMX
PRODUCTX
CONCATENATEXVARX.P | .S
STDEVX.P | .S
MEDIANX
PERCENTILEX.EXC | .INC
GEOMEANX
GrowTechie
Date table
CALENDARAUTO
Automatically creates a calendar table based on the database content.
Optionally you can specify the last month (for fiscal years).
GrowTechie
CALENDAR
Returns a table with a single column named “Date” containing a contiguous set of dates in
the given range, inclusive.
CALENDAR (
MIN ( Sales[Order Date] ),
MAX ( Sales[Order Date] )
)
GrowTechie
3.Needed to make time intelligence work if the relationship does not use a Date column
SalesAmount20150515 :=
CALCULATE (
SUM ( Sales[SalesAmount] ),
FILTER (
ALL ( 'Date'[Date] ),
AND ('Date'[Date] >= DATE ( 2015, 1, 1 ),
'Date'[Date] <= DATE ( 2015, 5, 15 )
)
)
)
GrowTechie
SalesAmount20150515 :=
CALCULATE (
SUM ( Sales[SalesAmount] ),
DATESBETWEEN (
'Date'[Date],
DATE ( 2015, 1, 1 ),DATE ( 2015, 5, 15 )
)
)
GrowTechie
SalesAmountYTD:=
CALCULATE (
SUM ( Sales[SalesAmount] ),
DATESBETWEEN (
'Date'[Date],
DATE ( YEAR ( MAX ( 'Date'[Date] ) ), 1, 1 ),MAX (
'Date'[Date] )
)
)
GrowTechie
SalesAmountYTD:=
CALCULATE (
SUM ( Sales[SalesAmount] ),
DATESBETWEEN (
'Date'[Date],
DATE ( YEAR ( MAX ( 'Date'[Date] ) ), 1, 1 ),MAX (
'Date'[Date] )
)
)
GrowTechie
SalesAmountYTD :=
TOTALYTD (
SUM ( Sales[SalesAmount] ),
'Date'[Date]
)
GrowTechie
SalesAmountYTD:=
SalesAmountYTD:=
Thank you
@Ramakrushnamohapatra
@growtechieind