0% found this document useful (0 votes)
78 views

Advanced DAX Power BI Power Pivot

Uploaded by

morgasss
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
78 views

Advanced DAX Power BI Power Pivot

Uploaded by

morgasss
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Advanced DAX Concepts

Course Notes
Leila Gharani
XelPlus.com

XelPlus.com
©Note: Copyright 2022, XelPlus.com, Leila Gharani, MA
Information
Course Notes for Advanced DAX for Excel Power Pivot
These course notes are accompanying documentation for my online course
Advanced DAX for Excel Power Pivot Course. Please do not reproduce or
transmit in any form without permission.
We have taken every effort to ensure the accuracy of this manual. In case
you discover any discrepancies, please send us a quick email to:
[email protected].

How to Use the Notes


Use these course notes alongside the online course to review and
revise each section of the course.
You can also print it out. Keep it handy and refer to it anytime the
need comes.

About Leila Gharani


Leila Gharani is a Microsoft MVP & a bestselling online course instructor.
She runs XelPlus.com an Office Productivity resource site to help people
gain the knowledge they need so they can create useful tools, solve
problems and get more done. She has a YouTube channel under her name
with more than 1 million subscribers.
Her background is: Masters in Economics, Economist, Consultant, Oracle
HFM Accounting Systems Expert & Project Manager. Find out more here.

XelPlus.com 2
(Power) Pivot Table Tips
Update Pivot Table Default Layout: File / Options / Data / Make Changes to
the Default Pivot Tables
(Possible in Excel for Office 365)

In case your Power Pivot Tab


disappears, you can activate
it from File / Options / Add-
ins / Manage:

Keep in Mind

Pressing save in the Data Model view, saves your


Excel files as well.

Refreshing the pivot table refreshes the queries


and the data model.

Others can use the workbook and create new


pivot tables from the data model without
refreshing the query. If they need the latest data,
they will need access to the source file.

XelPlus.com 3
DAX Engine Architecture
When you import tables to the Data Model, the data is stored in a Columnar
Database: Each column is stored separately and compressed. This is also
called the VertiPaq Storage Engine.

What Happens When Data is Refreshed?


• The Vertipaq Storage Engine reads the source data.
• Each table is split into separate columns.
• Each column is compressed with a map that tells the engine how to
reconstruct the data.
• Relationships are stored as pairs of IDs and row numbers.
• Calculated columns are calculated and compressed.

When working with large data sets, it’s suggested that


calculated columns be constructed outside of the Data
Model (ex: Power Query) and brought in as raw data.
This will reduce calculation times in the data model and
help to utilize similar compression strategies where
possible across the tables.

XelPlus.com 4
DAX Compression
Compressing data has several advantages:
The reduced size of the data occupies less memory in the model.
The time to scan the data is reduced.
Different compression techniques (i.e., algorithms) are applied to the
columns based on the column’s data type, data pattern, etc.

Value Encoding: This is a common form when dealing with columns of


integer numbers.

Hash Encoding: This is used to compress text-based columns (i.e., strings)


and other data types.

Run Length Encoding: This is responsible for compressing columns based on


unique/repetitive values.

Optimize your Data Model by…

Reduce the number of columns loaded to the data model. Specially


columns that have many different values.

Reduce the number of unique values in a column:


• The smaller the number of unique values in a column, the less
space the column takes.
• Round decimal numbers to the lowest possible digit.

XelPlus.com 5
DAX Iterator Functions
Iterator functions are functions that operate on each row of a table.
Examples of iterator functions include DAX aggregation functions, such as:
• SUMX
• AVERAGEX
• COUNTX

Using the “X” versions of these functions is required when you want to
process (i.e., iterate) through each row in a table, performing a calculation,
then aggregating all results into a single result.

An example of this is multiplying two columns (ex, sales and quantity) against
one another, then summing the results into a single total.

XelPlus.com 6
Evaluation Context
Understanding Evaluation Context is Crucial for Your Success
Context is used to determine how a formula evaluates data and produces a
result. There are two types of Contexts:
• Filter Context
• Row Context

Filter Context

The value presented is the result of having filtered the “Sales” table using
three separate filters.
[Department] = “Creative Arts”
[Month] = “February”
[State/Region] = “California”

Filters “transfer” from the one side of the relationship to the many side.
Not the other way round!

XelPlus.com 7
Row Context
Row Context is the knowledge of the current row.
The question is, “Which row?”
The row in question can come from the underlying tables or from a table
constructed by a formula.
Row Context exists in Calculated Columns & Measures that include
iterator functions.

[Total Sales] Measure is calculated based on the product of


[Quantity] and [SalesPrice] columns in the Sales Table.

Filter Context reduces the Sales table to the needed rows:


[Department] = “Creative Arts”, [Month] = “February”, [State/Region] =
“California”
Row Context then examines each row’s requested values (in this case,
[Quantity] and [SalesPrice]) to produce a calculation result for each row.
All row results are then aggregated.

XelPlus.com 8
Common DAX Functions
RELATED: This function gives you access to related columns. Related
columns are columns in your lookup / dimension tables that have a
relationship to your fact table.
The Related Function is commonly used in iterator functions that need to
access columns from other tables.
It’s also used in calculated columns.

Total Cost :=SUMX(Sales,Sales[Quantity]*RELATED(tblProduct[Cost]))

DIVIDE: It’s safer to use the DIVIDE function than the division operator.
DIVIDE can automatically handle division by zero or blank. You can also
define an alternate value directly in the function.

% Sales A to B :=DIVIDE([Total Sales]-[Budget Sales],[Budget Sales])

VALUES: This function returns a unique list of values based on the filter
context of your Pivot Table. This is a great function to use inside other
functions to perform calculations. For example, you can calculate average
daily sales with:

Average Daily Sales :=AVERAGEX(VALUES('Calendar'[Date]),[Total Sales])

ALL: The purpose of the ALL function is to return all rows from a table, or all
rows in a column, ignoring any filters that might have been applied. This
function is also typically used as a “remove filters” function inside
CALCULATE.

Count All Departments :=COUNTROWS(ALL(tblProduct[Department] ) )

XelPlus.com 9
FILTER Function
FILTER serves as a TABLE function but also as an iterator function
FILTER scans a table and performs row-by-row evaluations.
The FILTER function can take a full or partial table and reduce its rows based
on criteria. It filters a table.

FILTER SYNTAX
=FILTER(<table>, < filter>)

The <table> can be a full table from the Data Model or a table that is the
result of an expression (i.e., formula).
The <filter> is a Boolean expression that is evaluated on each row of the
supplied table. For example, [Sales] > 500 or [Country] = “Austria”.

Count of Orders where Quantity is greater Than 7


=COUNTROWS(FILTER(Sales, Sales[Quantity] > 7) )

The COUNTROWS function performs the actual row counting operation.


However, we need to feed the COUNTROWS function a subset of rows
from the “Sales” table.
Reducing the “Sales” table to only rows that have a value greater than 7 in
the [Quantity] column can be achieved using the FILTER function.

XelPlus.com 10
FILTER Function & Context
How does this function work?
COUNTROWS (
FILTER (
ALL ( dProduct ),
dProduct[RetailPrice]
> MAX ( dProduct[RetailPrice] )))

The red portion of the function is based on the “initial” filter context
created by the Pivot Table.
This means the Product Table is filtered to Sporting Goods and then the
Max retail price is calculated. This returns 103.98.

The ALL(dProduct) part of the function expands the Products Table and
dProduct[RetailPrice] is the row by row iteration. Each value is
compared to 103.98. There is only 1 value greater than this: 689.00.

XelPlus.com 11
CALCULATE Function
CALCULATE returns a Single Value
CALCULATE is the Only DAX function that can completely change the filters
coming from the Pivot Table.
CALCULATE is NOT an ITERATOR Function (although you can use Iterator
functions inside CALCULATE).
CALCULATE uses Relationships to access related tables.

The behavior of CALCULATE is like a Pivot Table.


CALCULATE Creates an invisible Pivot Table for each
Cell inside your existing Pivot Table.

CALCULATE SYNTAX

CALCULATE(<expression>[, <filter1> [, <filter2> [, …]]])

<filter> Can be written as a Boolean expression for example:


dProduct[Department]="office supplies“

Or <filter> can be written as a table expression


FILTER ( ALL (dProduct[Department]), dProduct[Department]="office
supplies")

Or <filter> can be a filter modifier function


ALL(Sales)
KEEPFILTERS(dProduct[Department]=“office supplies")

<expression> is calculated LAST. First all filters are applied and THEN the
expression is calculated.

XelPlus.com 12
CALCULATE Evaluation Steps
These are the evaluation steps for CALCULATE:

1 Filters Created by the Pivot Table are saved: Initial Filter Context.

2 CALCULATE checks its own filter arguments and creates a list of


values to add to the initial filter. Multiple filters are added with an
“AND” argument.

3 Initial filters are updated by adding these new filters. If a column is


“visible” in the Pivot Table, the field is replaced by the one from
CALCULATE.

4 Once this “invisible Pivot Table” fields are added to the Pivot Table,
the first argument in CALCULATE is calculated.

Find out more about CALCULATE Here: CALCULATE


function (DAX) - DAX | Microsoft Docs

Restrictions of “Boolean” Filters (in Power Pivot):


• Accept ONE column per argument.
• Cannot compare columns to other columns.
• Accept “hard coded” values – e.g., integer, text, variables.
• Cannot reference measures.

XelPlus.com 13
Context Transition
Context Transition is an important DAX Concept
Context Transition is the process by which all existing Row Contexts are
transformed into an equivalent Filter Context.

If a Measure is placed in front of a table row, it transforms each single


value on the row to a FILTER.

Measures are surrounded by a hidden CALCULATE.


[Total Quantity] := SUM(Sales[Quantity])
This is the same as
CALCULATE(SUM(Sales[Quantity]))

1 Measures are hungry for filters!


If you place a Measure in front of a table row, it will
treat each value as a filter. Similar to how measures
behave inside a Pivot Table. They “see” each row as a
filter.

2 Context transition can be an “expensive” process.


Use it on smaller tables (lookup tables) where possible
and avoid using it when you don’t need it.

3 Context Transition occurs whenever you are using a


Measure inside a function that iterates over a table.

XelPlus.com 14
Use Variables for More Clarity
The VAR keyword precedes the definition of a variable.
You can use multiple variables in a measure but when using variables, you
must use a RETURN statement to specify the final output to be returned.

Where:
<name> The name you want to use for the variable.
<expression>: A DAX expression which returns a scalar or table value.
<output_expression>: A DAX expression which returns a scalar or table
value.

NO Variables WITH Variables

IF(DISTINCTCOUNT(Sales[Date]) >28, var DC=DISTINCTCOUNT(Sales[Date])


"Busy", return
IF(DISTINCTCOUNT(Sales[Date])>25, IF(DC>28,"Busy",
"Usual", IF(DC>25,"Usual","Quiet"))
"Quiet"))

A variable
“stores the result of an expression as a named variable,
which can then be passed as an argument to other
measure expressions. Once calculated, the resultant
values for a variable expression do not change, even if the
variable is referenced in another expression.”

DAX variables are only available in PowerPivot for


Excel 2016 – They are not available in Excel 2013.

XelPlus.com 15
DAX Studio
DAX Studio is a free add-in you can download and install to:

• Debug problems with DAX code.


• Visualize results, both intermediate and final results.
• Check the performance of DAX operations.
• Assist in the understanding of DAX processes.

Install DAX Studio: DAX Studio - The ultimate client tool for
working with DAX queries

When evaluating a DAX function or a more complex DAX formula, type


the code in the Query Editor pane then click the Run button (or F5) on the
Home ribbon.
The DAX code must be preceded by the keyword EVALUATE.

XelPlus.com 16
THANK YOU!
Please take a few seconds to
leave a review for the course.
Your support is very much
appreciated.

XelPlus.com 17
More Learning…

If you’d like to improve your Spreadsheet knowledge, check out


my other courses at
www.XelPlus.com

If you’d like to learn Power Pivot & DAX from scratch and learn
how to create dashboards along the way, check out the
complete Power Pivot & DAX course at www.XelPlus.com

I share free content on YouTube every week. My Channel is


under my name.

You’ll find detailed blog posts and articles related to Excel,


PowerPoint, Outlook and other Office Products on my
Website at www.XelPlus.com

XelPlus.com 18

You might also like