0% found this document useful (0 votes)
85 views18 pages

DAX For Power BI: Sample Manual - First Two Chapters

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
85 views18 pages

DAX For Power BI: Sample Manual - First Two Chapters

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

DAX for Power BI

Sample manual - first two chapters

Manual 1293 - 126 pages –


TABLE OF CONTENTS (1 of 4)

1 INTRODUCTION TO DAX IN POWER Page 3 WORKING WITH DATA TYPES Page


BI
3.1 DAX Data Types 17
1.1 DAX in Power BI 6
Viewing a Column’s Data Type 17
How DAX is Used 1 – Calculated Columns 6
3.2 Working with Numbers 18
How DAX is Used 2 – Measures 6
How DAX is Used 3 – Calculated Tables 7 Basic Arithmetic 18
Choosing the Type of Calculation 7 Controlling the Calculation Order 18
Where Else is DAX Used? 7 Safely Dividing Numbers 19
Numeric Functions 20
1.2 The Construct-a-Creature Database 8
3.3 Working with Text 21
The Tables and Relationships 8
Writing Text in Calculations 21
1.3 Getting Help with DAX 9
Concatenating Text 21
Getting Help within Power BI 9
3.4 Text Functions 22
Other Sources of Help 9
Finding and Extracting Text 22
Replacing Text 22
2 BASIC CALCULATED COLUMNS Page Generating Text 23
2.1 Calculated Columns 10 Converting and Formatting Text 23

Key Features of Calculated Columns 10 3.5 Working with Dates 24


Creating a Calculated Column 10 Entering Date and Time Values 24
Entering a Formula 11 Returning the Current Date and Time 24
Calculated Column Properties 12 Calculating Date and Time Values 25
Using Calculated Columns in Visuals 12 Calculating the Difference Between Dates 25
2.2 Referencing Columns and Tables 13 Extracting Date Parts 26
Formatting Dates 26
Qualifying Column Names 13
Table Names 13
Referencing Columns in Other Tables 14 4 CONDITIONAL FUNCTIONS Page
The Related Function 14
4.1 The IF Function 27
2.3 Editing DAX Code 15
Testing a Single Condition 27
Multiple Lines and Indenting 15 Comparison Operators 27
Comments 16 The IN Operator 27
Keyboard Shortcuts 16 Nesting IF Functions 28
Combining Logical Tests 28
The NOT Operator 28

4.2 Working with Blanks 29


Producing a Blank 29
Blank Arithmetic 29
Testing for Blanks 29
The COALESCE Function 30

4.3 Testing for Errors 31


The ISERROR and IFERROR Functions 31
Avoiding Error Functions 31

4.4 The SWITCH Function 32


A Simple SWITCH Function 32
Logical Tests in a SWITCH Function 32

© Copyright 2024 Page 2


TABLE OF CONTENTS (2 of 4)

5 BASIC MEASURES Page 7 THE CALCULATE FUNCTION Page


5.1 Introduction to Measures 33 7.1 Introducing the CALCULATE Function 48
Measures vs. Calculated Columns 33 Expressions in the CALCULATE Function 48
Implicit Measures 33
7.2 Adding New Filters 49
5.2 Creating a Measure 34
Basic Filter Expressions 49
Adding a Measure to a Table 34 Adding Multiple Filters 50
Formatting Measures 35 Filter Arguments and Filter Context 50
Displaying a Measure in a Visual 35 Multiple Columns in Filter Arguments 51
Referencing Measures 36
7.3 Replacing Filters 52
5.3 Filter Context 37
Replacing an Existing Filter 52
What is Filter Context? 37 Comparing Differently Filtered Measures 53
How DAX Applies Filter Context 38 Dealing with Blank Values 53

5.4 Measures Tables 39 7.4 Keeping Filters 54


Creating a Separate Measures Table 39 The Problem with the Default Behaviour 54
Moving Measures 40 The KEEPFILTERS Function 55
Using the VALUES Function 55
5.5 Quick Measures 41
7.5 Removing Filters 56
Creating a Quick Measure 41
Editing a Quick Measure 42 Removing Every Filter 56
Using a Quick Measure 42 Using the ALL Function 57
Comparing Filtered and Unfiltered Values 57
Removing Filters from Specific Fields 58
6 AGGREGATION FUNCTIONS Page An Issue with Sort-By Fields 59
6.1 Aggregating Column Values 43 Removing Filters from a Specific Table 59

Basic Aggregation Functions 43 7.6 Special Filter Removal Functions 60


Functions for Counting 44 The ALLEXCEPT Function 60
Dealing with Boolean Values 44 The ALLSELECTED Function 61
6.2 Aggregating Expressions 45
The AggregateX Functions 45 8 VARIABLES Page
6.3 Iterators and Row Context 46 8.1 Introduction to Variables 62
A Reminder of Filter Context 46 Using Variables in Measures 62
Row Context in Iterator Functions 47
8.2 How Variables are Evaluated 63
The Final Result 47
How to Spot Iterators 47 Lazy Evaluation 63
DAX Variables are Constants 63

8.3 Debugging with Variables 64


Returning Different Variables 64

8.4 Nesting Variables 65


Variables in Functions 65
Variable Scope 66

© Copyright 2024 Page 3


TABLE OF CONTENTS (3 of 4)

9 THE FILTER FUNCTION Page 12 TIME INTELLIGENCE Page


9.1 Introduction to the FILTER Function 67 12.1 Introduction to Time Intelligence 86
A Basic FILTER Example 67 Calendar Tables 86
Using the CALCULATE Function 67 The Date Column 87
How CALCULATE and FILTER are 68 Referring to Calendar Tables 87
Related
Using Multiple Filters 68 12.2 Time Intelligence Functions 88
Using Variables 68 General Time Intelligence Functions 88
Using the DATEADD Function 88
9.2 FILTER vs. CALCULATE 69
How DATEADD Works 89
Referencing Multiple Fields 69 Using the DATESINPERIOD Function 89
Using Fields from Different Tables 69 Using the Current Date 90
Referring to Measures 70 Using Specific Dates 90
Replacing Filters 71
12.3 To Date Calculations 91
9.3 The CALCULATETABLE Function 72
Returning Date Ranges 91
Using CALCULATETABLE 72 Calculating Running Totals 91
Total To Date Functions 92
Easier Running Total Calculations 92
10 FILTERS AND RELATIONSHIPS Page Specifying Year End Dates 93
10.1 Relationships and Filter Direction 73 Calculating Life to Date Values 93

The Problem with Relationships 73 12.4 Next and Previous Periods 94


Changing the Cross Filter Direction 74
Next and Previous Period Functions 94
Solving the Problem using Filters 75
Comparing Entire Previous Years 95
10.2 Cross Filter Direction in Measures 76 Comparing Parts of Previous Years 96

The CROSSFILTER Function 76 12.5 Period Start and End Dates 97


Using Single and Both Filter Directions 77
Period Start and End Functions 97
Simultaneously
Start and End Dates 98
Multiple CROSSFILTER Functions 77
Opening and Closing Balances 99
First and Last Non-Blank Dates 99
11 CONTEXT TRANSITION Page First and Last Non-Blank Values 100
Non-Blank Opening Balances 100
11.1 What is Context Transition? 78
12.6 Moving Averages 101
Row and Filter Context 78
Calculating a Moving Average 101
11.2 Context Transition in Calculated 79
Columns
Row Context in Calculated Columns 79
Performing Context Transition 79
Implicit Context Transition 80
The RELATEDTABLE Function 80

11.3 Context Transition in Measures 81


Row Context in Measures 81
Context Transition in Measures 82
The Effect of Filter Context 82
Removing Filters 83

11.4 Ranking Values 84


The RANKX Function 84
Ranking in Calculated Columns 84
Context Transition in Calculated Columns 85
Ranking in Measures 85

© Copyright 2024 Page 4


TABLE OF CONTENTS (4 of 4)

13 CUSTOM CALENDARS Page 14 DYNAMIC MEASURES Page


13.1 Why use Custom Calendars? 102 14.1 Dynamic Labels 114
Disabling Automatic Calendars 102 Why use Dynamic Labels? 114

13.2 Creating a Custom Calendar 103 14.2 Returning a Single Value 115
The CALENDARAUTO and CALENDAR 103 The VALUES Function 115
Functions Testing for a Single Value 116
Adding Extra Columns 104 The SELECTEDVALUE Function 116
Financial Years 105
14.3 Concatenating Values 117
13.3 Finishing the Calendar 106
The CONCATENATEX Function 117
Marking as a Date Table 106 More Complex Expressions 117
Changing Default Aggregations 106
Setting Sort-By Columns 107 14.4 Filtered Values 118
Creating Hierarchies 107 Testing for Filtered Values 118
Hiding Fields 108 Testing for Cross Filtered Values 118
Creating a Relationship 108 Selecting the Top N Rows 119
13.4 Using a Custom Calendar 109 14.5 Disconnected Slicers 120
Creating Visuals 109 Creating a Disconnected Table 120
Time Intelligence Functions 109 Creating a Disconnected Slicer 121
Referencing the Selected Value 121
13.5 Multiple Date Fields 110
Using Multiple Calendars 110 14.6 Formatting with Measures 122
Using a Single Calendar 111 Calculating Colours with Measures 122
Changing the Active Relationship 111 Using Measures in Conditional 123
The USERELATIONSHIP Function 112 Formatting
Choosing Colours with Slicers 123
13.6 Special Dates 113

© Copyright 2024 Page 5


Chapter 1 - Introduction to DAX in Power BI

CHAPTER 1 - INTRODUCTION TO DAX IN POWER BI

1.1 DAX in Power BI

In Power BI you can use the DAX (Data Analysis eXpressions) language to create calculated
columns, measures and tables. You can see an example of each below.

How DAX is Used 1 – Calculated Columns

A calculated column is like a formula in an Excel table. The results of a calculated column are stored
in the data model.

This calculated column


gives the value for each
row of a sales table by
multiplying the price of
an item by the quantity
sold.

As we will see in this manual, a calculated column is evaluated for each row of a table; DAX uses
the row context to access the correct values for each separate calculation.

How DAX is Used 2 – Measures

A measure is a formula which calculates a value when you place it in a visual. The visual provides
a filter context which tells the measure which values it can use in the calculation.

This measure multiplies the price


of an item by the quantity sold for
each row of a sales table, then
sums the results.

When we place the measure in a


visual (a matrix in this case) the
measure is calculated for each
data point in the visual.

The filter context controls which


values the measure can access.
This cell gives the total sales
value for products in the Water
environment sold in the South
West region.

© Copyright 2024 Page 6


Chapter 1 - Introduction to DAX in Power BI

How DAX is Used 3 – Calculated Tables

Although most of the tables in your Power BI data model will be created by importing data, you can
also use DAX to calculate tables. It’s common to use this technique to create custom calendars.

This DAX expression creates a


calculated table which contains
a range of dates related to the
sales in our database.

Choosing the Type of Calculation

Power BI provides several ways to create calculated columns, measures and tables. One way is to
click the relevant tool on the Home tab of the ribbon while in the Data view.

Select the Data view tool on the left of the Power BI window.

The Calculations group on the Home tab of the ribbon has


a button for each type of DAX calculation.

Where Else is DAX Used?

In addition to Power BI, you can write DAX in the following applications:

Application Description
Power Pivot Power Pivot is an add-in for Excel which allows you to combine data from
multiple sources and present this in a pivot table or chart.
SQL Server Analysis Services SSAS Tabular Model allows you to combine data from lots of different data
(SSAS) Tabular sources, apply security to it to control who sees what and then allow
employees of your organisation to share the resulting data model.

© Copyright 2024 Page 7


Chapter 1 - Introduction to DAX in Power BI

1.2 The Construct-a-Creature Database

This courseware uses data from the (fictitious) Wise Owl subsidiary Construct-a-Creature (a retail
chain loosely modelled on Build-a-Bear, but with a wider range of animals available for purchase).

The Tables and Relationships

You can see the tables and relationships of the database in the diagram below:

There are four tables representing a geographical dimension to do with where sales took place. These tables give
the shopping centre, type of centre, town and region.

There are also four tables representing a product dimension. These give The Sales table stores how many
details of the product sold (for example, a frog is an amphibian which of each product were sold in each
lives in a fresh water habitat in a watery environment). transaction.

© Copyright 2024 Page 8


Chapter 1 - Introduction to DAX in Power BI

1.3 Getting Help with DAX

The amount of help available for DAX both within Power BI and from third parties has increased
dramatically since the product was first released.

Getting Help within Power BI

You’ll see various popups appear to help you as you write DAX in Power BI.

When you use a DAX function, a


popup shows you a description of
what it does and which parameters
you need to fill in.

The Intellisense list helps you to


pick functions and column names
to save on typing.

Other Sources of Help

You can find more descriptive help for DAX on a range of websites, as shown in the table below:

Website Description URL


Microsoft DAX Microsoft’s official documentation for DAX https://learn.microsoft.com/en-us/dax/
Reference functions. It’s somewhat dry but a useful
technical reference.
Power BI A Microsoft forum in which you can post https://community.fabric.microsoft.com/
Community questions about any aspect of Power BI and t5/Microsoft-Power-BI-Community/ct-
rely on other members to provide answers. p/powerbi
SQLBI A third-party site maintained by Marco Russo https://www.sqlbi.com/
and Alberto Ferrari. The site contains lots of
free resources to help you with DAX.
DAX Guide A third-party alternative to Microsoft’s DAX https://dax.guide/
Reference created by the Italians. This site
fleshes out the detail of DAX functions and
provides links to helpful articles which
describe in more detail how the functions
work.
Wise Owl The Wise Owl website contains lots of free https://www.wiseowl.co.uk/resources/
resources including videos, blogs and
exercises to help you with learning DAX.

© Copyright 2024 Page 9


Chapter 2 - Basic Calculated Columns

CHAPTER 2 - BASIC CALCULATED COLUMNS

2.1 Calculated Columns

A calculated column is a type of calculation you can create using DAX in Power BI. This chapter
shows you the basics of writing DAX using calculated columns.

Key Features of Calculated Columns

You can see some of the key features of calculated columns in the table below:

Feature Description
Created in data tables You create a calculated column in a table in the data model. The calculated
column can refer directly to any column in the same table.
Calculated immediately A calculated column produces its results as soon as you enter it. The values
are updated whenever the data model is refreshed.
Stores data in the model A calculated column stores its results in the data model. Each calculated
column you create increases the storage space required by the model.
Uses row context The expression in a calculated column is evaluated for each row in the table.
The row context provides the expression with access to values on the same
row in the table.

Creating a Calculated Column

You can create a calculated column in any of the three Power BI views but, if you want to see the
results of your calculation, it’s best to select the Data view.

Select the Data view button on the left of the Power


BI window.

You can right-click on any column in the table and


choose New column to add a calculated column.

You can choose New column from the You can right-click the table in the Data
Table tools or Home tabs of the ribbon panel and choose New column to add a
to add a calculated column. calculated column.

© Copyright 2024 Page 10


Chapter 2 - Basic Calculated Columns

Entering a Formula

After choosing to create a calculated column you can enter your DAX code in the formula bar below
the ribbon. The example below multiplies one column by another to create a new value:

1) Start by giving the column a sensible name.

Change the text on the left of the


equals sign to rename the column.

2) To reference a column in the same table, simply begin typing the column name.

As you type, the Intellisense list will filter the


list of matching column and function names.

Highlight the item you want to insert and


press Tab to insert it into the formula.

3) Type in an operator then reference the next column.

You can use spaces in a DAX formula to make it more readable.


Here we’ve added spaces around the multiply operator.

4) Press Enter to commit the formula.

You can also click the tick When you complete the formula, DAX calculates
to commit the formula. an answer for each row of the table.

Your calculated column will appear in the table in the Data pane with a special symbol to indicate its
status.

This symbol indicates that


the column is a calculated
column.

© Copyright 2024 Page 11


Chapter 2 - Basic Calculated Columns

Calculated Column Properties

Once you’ve created a calculated column, you can modify it in the same way as any other column
in your data model, as shown in the diagram below.

Select the column in the You can change the default


Data pane. You can then aggregation function used
use the Column tools tab when you add the column to
in the ribbon to modify its a visual using this drop-down
properties. list.

You can apply formatting to the column You can assign a data category to the column
using these tools. using this drop-down list.

Using Calculated Columns in Visuals

You can use a calculated column to populate visuals in your report, just as for any other column in
your data model.

If the calculation produces


text, you can use it to
populate category fields in a
visual. Here we’ve used a
calculated column called
Centre Size to group the
values in a chart.

You can assign numeric


calculated columns to value
fields in a visual. Here
we’re using the Sale Value
calculated column to create
a sum of sale value.

© Copyright 2024 Page 12


Chapter 2 - Basic Calculated Columns

2.2 Referencing Columns and Tables

This section shows you various ways to refer to columns and tables in your DAX formulae.

Qualifying Column Names

When you select a column name from the Intellisense list, it will be automatically qualified with the
name of the table to which it belongs. You don’t have to include the table name, however.

These two formulae


give the same result.

Although you don’t always have to include the table name when referencing a column, it makes
sense to do so for the following reasons:

• If you always include the table name you don’t have to remember when it is or isn’t required.

• It allows you to spot when you’re referring to a column as opposed to, say, a measure.

• When a column name exists in multiple tables it makes the reference unambiguous.

Table Names

If the name of a table contains spaces, or it conflicts with another DAX keyword, you must enclose
the table name in single quotes.

Sales Table must be enclosed in


single quotes due to the space in
the table name.

Wise You can always enclose a table name in single quotes, even when it isn’t required.
Owl’s
Hint

© Copyright 2024 Page 13


Chapter 2 - Basic Calculated Columns

Referencing Columns in Other Tables

In a calculated column you can only directly reference other columns which belong to the same table.
This is a problem when your calculation needs to refer to columns in other tables!

We’d like to create a calculated column in the


Sales table which multiplies the Quantity by
the ProductionCost in the Product table.

When we reference the ProductionCost


column directly, the formula results in an
error.

The Related Function

The key to solving the above problem is that the Product and Sales tables have a relationship. This
allows us to use the RELATED function to reference a column in a related table.

We can successfully reference


the ProductionCost column by
using the RELATED function.

You can reference columns from a table at the 1 end of a relationship, regardless of how many steps
it takes. In our model, the Sales table sits at the many end of every relationship:

A calculated column in
the Sales table can
reference any other
column in the data
model using the
RELATED function.

In the Sales table you


could return the
RegionName with this
formula:
=RELATED(
Region[RegionName]
)

© Copyright 2024 Page 14


Chapter 2 - Basic Calculated Columns

2.3 Editing DAX Code

Although you can write a DAX formula as a continuous stream of code, there are several things you
can do to make your code more readable.

Laying out a formula


like this makes it very
difficult to work with!

Wise It’s not important to understand what the code in this section does – instead, focus
Owl’s
Hint
on the techniques used to make it more readable.

Multiple Lines and Indenting

You can break a formula onto multiple lines and add tab spaces to make it more readable. You can
use the following keys to add new lines and indenting to a formula:

Key What it does


Shift + Enter or Alt + Enter Adds a new line, and a tab level if appropriate.
Tab Indents the highlighted lines one tab space.
Shift + Tab Outdents the highlighted lines one tab space.

You can see an example of a formula with new lines and indenting in the diagram below:

When you use a function Each new function that


(in this case DIVIDE), you use should have its
open the round brackets arguments indented one
then start a new line and extra tab level.
add a tab space.

All of the arguments for


a single function should
Close the brackets for a be at the same tab level.
function at the same
indent level as the line
on which the brackets
were opened. Use the
vertical grey lines to help Use a comma at the end
you put the brackets in of a line to separate one
the right place. argument from the next.

© Copyright 2024 Page 15


Chapter 2 - Basic Calculated Columns

Comments

You can use comments to annotate your code. You can add a comment at the end of any line after
the = sign in a formula.

You can type // to begin adding


a comment, followed by the
comment text.

You can also begin a comment


using -- rather than //.

Start a multi-line comment with


/* and end it with */ as shown
here.

Keyboard Shortcuts

You can use a range of keyboard shortcuts to help you edit your DAX code. You can see some of
these in the table below:

Key What it does


Ctrl + G Goto the specified line number.
Alt + ↑ / Alt + ↓ Move the line of code up / down.
Shift + Alt + ↑ / Shift + Alt + ↓ Copy the line of code up / down.
Ctrl + Shift + \ Jump to the paired bracket.
Alt + Left mouse click Add a text cursor at the clicked position.
Ctrl + L Select the line of code.
Ctrl + Shift + L Select all occurrences of the current selection.
Ctrl + F2 Select all occurrences of the current word.
Ctrl + / Comment/uncomment the line of code.
Ctrl + = / Ctrl + - Zoom in / zoom out.
Ctrl + Space Bar Show the Intellisense list.
Ctrl + I Show and hide tooltips.
Ctrl + J Expand and collapse the formula bar.

© Copyright 2024 Page 16


What we do!

Basic Advanced Systems /


training training consultancy

Microsoft Excel

VBA macros
Office

Office Scripts

Microsoft Access

Power BI and DAX


Power BI, etc

Power Apps

Power Automate (both)

SQL

Reporting Services
SQL Server

Report Builder

Integration Services

Analysis Services

Visual C#
Coding and AI

VB programming

AI tools

Python

www.wiseowl.co.uk | (0161) 883 3606 | [email protected]


www.wiseowl.co.uk | (0161) 883 3606 | [email protected]

You might also like