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

Power-BI-DAX-Essentials_AMZ_Manual_Snippet

The document titled 'Power BI DAX Essentials' serves as a comprehensive guide to the Data Analysis Expression (DAX) language used in Power BI. It covers various topics including data modeling, calculated columns and measures, basic and advanced DAX functions, evaluation contexts, and practical applications of DAX concepts. The content is structured into chapters that provide detailed explanations, examples, and best practices for effectively utilizing DAX in data analysis.

Uploaded by

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

Power-BI-DAX-Essentials_AMZ_Manual_Snippet

The document titled 'Power BI DAX Essentials' serves as a comprehensive guide to the Data Analysis Expression (DAX) language used in Power BI. It covers various topics including data modeling, calculated columns and measures, basic and advanced DAX functions, evaluation contexts, and practical applications of DAX concepts. The content is structured into chapters that provide detailed explanations, examples, and best practices for effectively utilizing DAX in data analysis.

Uploaded by

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

Power BI DAX ESSENTIALS

Power BI DAX Essentials


Copyright © 2021 by AMZ Consulting Pty Ltd
Published by Dynamic Web Training

Brisbane | Melbourne | Sydney | Adelaide | Perth | Canberra | Online


Australia
Phone: 1300 888 724
Web: www.dynamicwebtraining.com.au/
Email: [email protected]
Product Code: PBIv3.00
Build: 01/04/21
Trademark Acknowledgments
All terms mentioned in this manual that are known to be trademarks or service marks have
been appropriately acknowledged or capitalized. Dynamic Web Training cannot attest to the accuracy
of this information. Use of a term in this manual should not be regarded as affecting the validity of
any trademark or service mark.
Screen Shots © 1983-2018 Microsoft. All rights reserved.
Disclaimer
Every effort has been made to provide accurate and complete information. However, Dynamic
Web Training assumes no responsibility for any direct, indirect, incidental, or consequential damages
arising from the use of information in this document. Data and case study examples are intended to be
fictional. Any resemblance to real persons or companies is coincidental.
Copyright Notice
This publication is protected in accordance with the provisions of the Copyright Act. Apart
from permissions expressed in the Copyright Act pertaining to copying for study, review, or research,
no part of this publication may be reproduced in any form, or stored in a database or retrieval system,
or without written permission from AMZ Consulting Pty Ltd.
TABLE OF CONTENTS

Contents
Chapter 1: Getting to Know Data Analysis Expression (DAX) language 6
What is DAX? 6
Perquisites: 7
Where is DAX used? 8
What are the Data types in DAX 9
Numerical data types: 9
Non-numerical data types: 9
Variant Data Type: 9
DAX type handling/operator overloading 10
Addition of two “string” inputs: 10
Concatenation of two “numbers”: 10
DAX as Formula Language 11
Vertipaq engine in DAX 12
Value Encoding: 12
Dictionary or Hash Encoding: 12
Run Length Encoding (RLE): 12
Factors Affecting Model Compression: 12
Difference between DAX and EXCEL functions 14
Difference between DAX and M 15
Best Practices in DAX 16
Dos, and Don'ts and Best Practices in DAX 17
Chapter 2: Data Modeling Recap 19
What is Data Model 20
Tables in a Data Model 21
Fact Table / Data Table 21
Dimension Table / Lookup Table: 21
Fact vs Dimensions 22
Schemas in Data Model 23
Star Schema 23
Snowflake Schema 26
Why star Schema is Preferred 27
Filter Propagation 28
Interpreting Mechanism for Filtering 29
Using Multiple Filters together 30
Data Denormalization 31
Relationship Characteristics 32
Cardinality 32
Filter Direction 32

Page | 1
TABLE OF CONTENTS

Apply Security Filter in Both Directions 33


Active 33
Assume Referential Integrity 33
Chapter 3: Calculated Columns and Measures 34
Getting Started 35
Calculated Column and its use case 36
When do Calculated Columns fail 38
Calculated Measure and its use case 40
What is a Calculated Measure: 40
When to use Calculated Column or Calculated Measure 43
Calculated Column vs. Calculated Measures 44
Chapter 4: Basic DAX Functions 46
Two broad categories of functions in DAX 47
Regular Functions 47
Iterator Functions 47
Use of DIVIDE() and COUNT() 48
DIVIDE(): 48
COUNT(): 49
Counting Rows 51
COUNTROWS(): 51
Use of DISTINCTCOUNT () 52
Finding Min, Max and Average 53
MIN() 54
MAX(): 54
AVERAGER(): 55
Counting Blank Values 57
COUNTBLANK(): 57
Chapter 5: Evaluation Contexts in DAX 59
What are the two evaluation contexts in DAX? 60
Row Context: 60
Filter Context: 60
What is initial or incoming filter context 61
What is Row Context 63
Row context using Calculated Column: 63
Row context using Calculated Measure: 63
Filter Context vs Row Context 64
Evaluation Context in Functions 65
Rules of Evaluation 66
Chapter 6: Related Functions and Context Transition 67
Using RELATED() 68
Using RELATEDTABLE() 70

Page|2
TABLE OF CONTENTS

RELATED() vs. RELATEDTABLE() 72


Introduction to Context Transition 73
Last Order Date of a Customer: 74
Row to Filter Context transition 76
Chapter 7: Table Functions 77
Creating a Calculated Table 78
Using VALUES() 79
Values using table name as argument: 79
Values using column name as argument 81
DISTICT vs. VALUES() 82
Using ALL() to ignore Filters 83
ALL() using single column: 83
ALL() using multiple columns: 84
Creating summary table for the requested totals using SUMMARIZE() 86
Totals over a Group-by column: 86
Totals over a multiple Group-by columns: 86
SUMMARIZE() using measure or expression for GroupBy: 87
Adding columns from other data tables: 89
Using SUMMARIZE() to get data for all categories: 90
Using ALLEXCEPT() 93
Using FILTER() as a Table function 94
Filter Using Multiple Conditions: 95
Virtual table lineage 96
Mixing table functions 97
ALL and Filter 97
Summarize and Filter 99
The Cross Join 101
CROSSJOIN() with VALUES() 102
Exploring Table Joins 103
Testing table functions in measures 104
Understanding the difference between VALUES(), DISTINCT(), ALL() and
ALLNOBLANKROW 108
Chapter 8: Variables and Comments in DAX 112
Creating Variables 113
Features of a Variable 114
Conditional Computations using Variables 116
Location of Variable Evaluation 117
Increasing Code Readability 118
Improving code Readability: 118
Variables for debugging: 119
Writing single and multi-line comments 121

Page|3
TABLE OF CONTENTS

Single line comments: 121


Multi line comments 121
Chapter 9: Creating Date Table 122
Creating & Optimizing Calendar Table using DAX functions 123
Using CALENDERAUTO(): 123
Using CALENDER(): 124
Marking as Date Table 128
Adding Date Columns 129
Creating YEAR() Column: 129
Creating MONTH() Column: 129
Creating QUARTER() Column: 130
Formatting the Columns: 131
Working with Fiscal Years 133
Finding Weekday 135
Calculating WEEDAY(): 135
DAX Date Template: 136
Creating Relationship 137
Set sorting options 137
Chapter 10: Basic Iterators 139
Iterators vs. Aggregator Functions 140
Using SUMX() 141
Using AVERAGEX() 144
Using MINX() and MAXX() 147
Using MINX(): 147
Using MAXX(): 147
Implicit CALCULATE() and Context Transition 150
What happens behind the scene? 151
Average Sales per Product: 153
Average Sales Amount: 153
Chapter 11: Advance Filtering in DAX 155
Modification of Filter context using CALCULATE() 156
Modify how filters are applied using KEEPFILTERS() 158
Modification of multiple filters with CALCULATE() 160
Using FILTER() with CALCULATE() 164
Return all the rows in a table using All() 166
Using Filter modifiers 168
Using ALLSELECTED() 170
Chapter 12: Time Intelligence in DAX 172
What is Time Intelligence 173
Date table properties for Time Intelligence 173
Aggregations over time 174

Page|4
TABLE OF CONTENTS

Using DATE(): 174


Using DATEBETWEEN(): 175
Total Year till Date, Month till Date and Quarter till Date 177
Using DATESYTD(): 177
Using TOTALYTD(): 178
Handling Fiscal Year 181
Same Period Last Year 182
Using DATEADD(): 182
Using SAMEPERIODLASTYEAR(): 184
Finding YOY % 186
Quick Measures Option: 187
Using PARALLELPERIOD() 189
Finding Moving Total 192
Calculate Running Total 194
Chapter 13: Conditionals in DAX 195
Use of IF() statements 196
Using SWITCH() 198
Switching between cases using SWITCH() 202
Finding your text 204
Chapter 14: Practical Use of Concepts and Other Functions 206
Using CONCATENATEX() 207
CONCATENATEX() with HASONEVALUE() 209
Using ISINSCOPE() 211
Expected Result: 212
Using ISINSCOPE(): 212
Parameter table and SELECTEDVALUE() 217
Using RANKX() 219
Static Ranking: 219
Dynamic Ranking: 221
ISINSCOPE() with RANKX() 223
Counting spikes 225
Setting the threshold: 225
Finding the High Months: 225
Using PREVIOUSMONTH(): 227
Finding the Spikes: 227
Chapter 15: Hierarchies In DAX 229
What are hierarchies 230
Parent-Child Hierarchy: 230
Final Expected Result: 231
Using Path functions to traverse hierarchy 233
Creating Levels 234

Page|5
TABLE OF CONTENTS

Using PATHITEM() 234


Using LOOKUPVALUE() 234
Finding Maximum Depths 237
Determining Browsing Levels 238
Analyzing Sales in Hierarchies 240
Chapter 16: DAX Tools and Other Resources 242
Common errors, causes and debugging 243
Missing Row Context: 243
Wrong Column Reference: 244
Wrong Measure Reference: 244
What is DAX Formatter 245
Setting the mode: 246
What is DAX Studio 248
Useful Features of DAX Studio: 248
Downloading and Installing DAX Studio 250
Operating system requirements 250
Installation Options: 250
Connecting DAX studio with Power BI 254
Launching it directly from your system 254
Launching from Power BI Desktop 254
Getting Started with DAX Studio 256
Metadata Panel 256
The Ribbon 257
The Query Pane: 259
Output, results and history pane 259
Writing Queries in DAX Studio 261
EVALUATE statement: 261
Query Builder: 261
Top 10 Product’s contribution to Sales Revenue 263
Categorizing Low, Medium and High-value Sales 268
SUMMARIZE() vs. SUMMARIZECOLUMNS(): 271
Top three products in each product subcategory 272
Using CALCULATETABLE() 274

Page|6
CHAPTER 5: EVALUATION CONTEXT IN DAX

Chapter 5: Evaluation Contexts in


DAX

Page|7
CHAPTER 5: EVALUATION CONTEXT IN DAX

What are the two evaluation contexts in DAX?


Any DAX function is evaluated under a context. Evaluation context is an
“environment” in which the formula is calculated.
There are two types of evaluation context which are completely different from each
other.

Row Context:
When you write an expression in a calculated column, the expression is evaluated for
each row of the table, creating a row context for each row. In a similar manner, when you use
an iterator like FILTER(), SUMX(), AVERAGEX(), ADDCOLUMNS(), or any one of the DAX
functions that iterates over a table or a table expression, it creates a row context.
A row context is evaluated whenever an expression iterates over a table. Row context
does not follow relationships and does not create a filter context. DAX functions are used to
covert a row context into a filter context.
A row context exists in either a calculated column or an iterating function such as
SUMX(). It does not exist in a regular measure. This is because regular measures cannot be
created using naked columns. Regular measures only operate on columns and tables so the
row filtering does not come into play using measures unless the iterator function is used.

Filter Context:
Filter context is evaluated based on filtering applied on the data model in DAX. The
Initial/Incoming filter context comes from

✔ Slicers

✔ Data Fields of a visual (e.g. Rows and Columns in Matrix)

✔ Page or Report Filters

✔ From other visuals

Filter context can be modified or replaced by using CALCULATE() function. Filters


otherwise automatically follows relationships from 1 to many side.

Page|8
CHAPTER 5: EVALUATION CONTEXT IN DAX

What is initial or incoming filter context


The initial filters applied on the report in the form of slicers, page and report filters.
Visual filters act as the first-hand filtering before evaluation context is evaluated.
Continue using the previous file for the exercise or open the file
Evaluation_Context_In_DAX_1.pbix..
To see the effect of initial or incoming filter context.
1. Click on the matrix in the visualization pane.
2. Add the Category from the Product to the rows.
3. Add the Sales Amount and Unit Price Discount Pct from the Sales table to the
values
4. Right click on the Unit price Discount Pct in values and change the Calculation
to Maximum.
5. Drag and drop the Color column from the Product table to the Filters pane.
6. Select the checkbox next to silver in the filter.
7. Click on Slicer in the Visualization Pane.
8. Drag and drop Channel from SalesOrder table into the Fields.
9. Click on Slicer in the Visualization Pane.
10. Drag and drop Country from SalesTerritory table into the Fields.
11. Click on Internet in the Channel slicer.
12. Click on Australia in the Country slicer.

Notice that the value in the red box is dependent on:

Page|9
CHAPTER 5: EVALUATION CONTEXT IN DAX

✔ Filter on the Rows of matrix.

✔ Filter on the Column of matrix (which specifies the calculations).

✔ The page level filter for product color.

✔ The filter by slicer by slicing data for channel.

✔ The filter by slicer by slicing data for one country only.

Notice that no discount has been provided using the selected filter values.

13. Click on Reseller in the Channel slicer.

Notice the change in values. This means that the Unit price discount was applicable
for purchases through resellers only.

P a g e | 10
CHAPTER 5: EVALUATION CONTEXT IN DAX

What is Row Context


A row context is created when any DAX expression is evaluated for each row. Row
context can be created by:

Row context using Calculated Column:


When a calculated column is created, the expression for the values in the new column
are evaluated for each row value. This creates a row context. Therefore, any function used for
creating a calculated column in Power BI creates a row context.

Row context using Calculated Measure:


Measures may or may not create a row context. If the measure is created using an
iterator function, then the expression is evaluated for each row and therefore a row context is
created. Whereas, if the measures use regular functions then no row context is created.

P a g e | 11
CHAPTER 5: EVALUATION CONTEXT IN DAX

Filter Context vs Row Context


There are always two contexts in DAX and these are known as the pillars of DAX.
Let’s look at some basic differences between these two:

Filter Context Row Context


Context creation Provided by coordinates of the Exists in Calculated
visual Column or iterative DAX
functions
Role of CALCULATE() CALCULATE() function can CALCULATE() can convert
be used to alter a filter context. a row context to a filter
context.
Relationships Automatically follow the Does not follow
relationships from the 1 to relationships or create a
many side. filter context.

P a g e | 12
CHAPTER 5: EVALUATION CONTEXT IN DAX

Evaluation Context in Functions


Let’s look at some example of the evaluation contexts in functions.

✔ RELATED(): This function expands the row context of the current row and allows
you to perform VLOOKUP to include values in a column.
✔ FILTER(): This function allows you to specify a subset of data to include in the
current context.
✔ ALL(): This function sets a new context by ignoring the existing filter context.

✔ ALLEXCEPT(): This function lets you remove all the filter except the specified one.
Thereby, changing the existing filter context.
✔ EARLIER() or EARLIEST(): These functions let you perform calculations in loop by
referencing to a value in the inner loop.

P a g e | 13
CHAPTER 5: EVALUATION CONTEXT IN DAX

Rules of Evaluation
When a DAX expression is evaluated there are a series of rules that are executed in
order. They form the foundation of how you will use DAX functions.
The Rules for evaluation of DAX Expression are:

✔ Evaluation of the Initial/Incoming filter context from Slicers.

✔ Data Fields of a visual (e.g. Rows and Columns in Matrix).

✔ Page or Report Filters.

✔ From other visuals.

✔ If CALCULATE () is used, Check for Filter modification.

✔ Check for applied filter to underlying table(s)

✔ Interpret the filter propagation per relationship(s).

Evaluate the result after catering the effect of the above mentioned filters.

This will be easier to understand once we create some expressions to demonstrate


how the evaluation evolves.
There are many exceptions and variations to these rules but will intentionally
overlook these nuances to make things simple and more generic. This will allow you to
understand the most important fundamentals without getting bogged down by complex
details. All those exceptions to the rules are important but I believe you should only go these
once you’ve spent enough time practicing these fundamentals and have deep understanding
of it.

P a g e | 14
CHAPTER 6: RELATED FUNCTIONS AND CONTEXT TRANSITION

Chapter 6: Related Functions and


Context Transition

P a g e | 15
CHAPTER 6: RELATED FUNCTIONS AND CONTEXT TRANSITION

Using RELATED()
Now that you’re familiar with the basic DAX functions, lets look at some functions
which can help you fetch data from other tables.
Continue using the previous file for the exercise or open the file
Related_Functions_and_Context_Transition_1.pbix..

RELATED() takes value from the one side of the one-to-many relationship and
populates it to the many side of the relationship. To use RELATED() for bringing the list
price value from the Product table into the Sales table:
1. Right click on the Sales table in the Fields Pan.
2. Click on New Column.
Column tools open.
3. Type the following formula in the formula bar.

Notice that the intellesence detects that currently List Price does not exist in Sales
Table. So intellisense does not give option to select a column from the Product table. We will
use RELATED() function to activate the relationship.
4. Type RELATED in the formula bar after =.
5. Select the List Price from the Product table.
Your DAX expression should look similar to the expression below.

In this Expression:
⮚ A calculated column with each row containing the respective List Price from
the Product table has been created.
6. Click on Data tab in the left Ribbon.
7. Click on Sales table in the Fields.

P a g e | 16
CHAPTER 6: RELATED FUNCTIONS AND CONTEXT TRANSITION

Notice the current list price column at the end.

P a g e | 17
CHAPTER 6: RELATED FUNCTIONS AND CONTEXT TRANSITION

Using RELATEDTABLE()
RELATEDTABLE() takes values from the many side of the one-to-many relationship
and populates the one side of the relationship.
Continue using the previous file for the exercise or open the file
Related_Functions_and_Context_Transition_2.pbix..
Since there are multiple values for RALTEDTABLE() takes the table name as the
input argument.

To use the RELATEDTABLE() function for calculating the number of sales in


Customer Table:
1. Right click on the Customer table in the Fields pan.
2. Click on New column.
Column tools open.
3. Type the following formula in the formula bar and press Enter.

In this Expression:
⮚ The rows in the Sales table have been counted.
4. Click on Data tab in the left Ribbon.
5. Click on Customer table in the Fields pan.

As you can see, row context does not follow relationship. RELATEDTABLE() allows
us to traverse the chain of relationship.
6. Click on the Number of Sales (CC) column.
Column tool box appears containing the formula bar.
7. Add RELATEDTABLE() before the sales in the formula.
Your DAX expression should look similar to the expression below.

P a g e | 18
CHAPTER 6: RELATED FUNCTIONS AND CONTEXT TRANSITION

In this Expression:
⮚ The related number of rows from the sales table are counted based on the
incoming filter context.
Notice the change of values in the Number of Sales (CC) column.

The Number of Sales (CC) gives the number of Sales transactions by each customer.

P a g e | 19
CHAPTER 6: RELATED FUNCTIONS AND CONTEXT TRANSITION

RELATED() vs. RELATEDTABLE()


RELATED() and RELATEDTABLE() are the two functions used to traverse
one-to-many relationship in DAX. The few key differences between the two functions are:
RELATED() RELATEDTABLE()
Input Argument Column name Table name
Output Single value from the A table of values
current row.
Takes values from one side of relationship many side of the relationship
Populates many side of the relationship one side of relationship

P a g e | 20
CHAPTER 6: RELATED FUNCTIONS AND CONTEXT TRANSITION

Introduction to Context Transition


Now let’s create another calculated column which shows the number of distinct
products purchased by a customer. When you create this calculated column, you will face the
same problem but this time you cannot use RELATEDTABLE() function as it only accepts a
table argument. So for this, you will put DISTINCTCOUNT() on Sales[ProductKey].
Continue using the previous file for the exercise or open the file
Related_Functions_and_Context_Transition_3.pbix..
To find number of distinct products bought by a customer:
1. Right click on the Customer table in the Fields pan.
2. Click on New column.
Column tools open.
3. Type the following formula in the formula bar and press Enter.

In this Expression:
⮚ The unique product keys from the Sales table are counted.
4. Click on Data tab in the left Ribbon.
5. Click on Customer table in the Fields pan.
6. Click on the drop box at the top on Number of Products Purchased (CC).
7. Click on Sort Descending.

The result is not correct because all of the customers cannot buy the same number of
products. However, CALCULATE() allows us to get the result. Calculate converts Row
context into filter context. This is called context transition. CALCULATE() will be
discussed in more detail later in the course.
8. Click on the Number of Products Purchased (CC) column.
Column tool box appears containing the formula bar.
9. Add CALCULATE() before the DISTINTCOUMT() in the formula and press
Enter.
Your DAX expression should look similar to the expression below.

P a g e | 21
CHAPTER 6: RELATED FUNCTIONS AND CONTEXT TRANSITION

In this Expression:
⮚ The filter context is modified by CALCULATE().
10. Click on the drop box at the top on Number of Products Purchased (CC).
11. Click on Sort Descending.

In the example below, you can see Nancy Chapman had 57 sales but only bought 22
different products.

Last Order Date of a Customer:


To find last order date by a customer using context transition:
12. Right click on the Customer table in the Fields pan.
13. Click on New column.
Column tools open.
14. Type the following formula in the formula bar and press Enter.

In this Expression:
⮚ The MAX() function finds the latest order date in the Sales Table.
⮚ CALCULATE() modifies the filter context so that the last order date for each
customer can be filtered.
15. Format the Last Order Date (CC) column to (m/d/yy).
16. Click on Data tab in the left Ribbon.
17. Click on Customer table in the Fields pan.

P a g e | 22
CHAPTER 6: RELATED FUNCTIONS AND CONTEXT TRANSITION

Notice that Nancy last ordered on 12th of June, 2020.

It is important to format the newly created columns to the format used in your organization.
For this course we have followed the m/d/yy format for the date.

P a g e | 23
CHAPTER 6: RELATED FUNCTIONS AND CONTEXT TRANSITION

Row to Filter Context transition


As you have seen in the last exercise, CALCULATE() is used to perform row to filter
context transition. The image below depicts what row to filter context transition looks like.

Row context does not follow relationships but filter context does follow relationships.
So CALCULATE() take the current row, transform it into a filter context and after
CALCULATE transitions to the new filter context (before the expression in CALCULATE is
evaluated) the CustomerKey value will filter records in the Sales table.

P a g e | 24

You might also like