6 Introduction To Creating Measures Using DAX in Power BI

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 97

Introduction to creating measures

using DAX in Power BI


 2 hr 40 min
 Module
 10 Units
 4.7 (5,651)
Rate it
Intermediate
Data Analyst
Power BI
Microsoft Power Platform

Data Analysis Expressions (DAX) is a programming language that is used throughout


Microsoft Power BI for creating calculated columns, measures, and custom tables. It
is a collection of functions, operators, and constants that can be used in a formula, or
expression, to calculate and return one or more values. You can use DAX to solve a
number of calculations and data analysis problems, which can help you create new
information from data that is already in your model.

Learning objectives
By the end of this module, you'll be able to:
 Build quick measures.
 Create calculated columns.
 Use DAX to build measures.
 Discover how context affects DAX measures.
 Use the CALCULATE function to manipulate filters.
 Implement time intelligence by using DAX.
StartSave

Prerequisites
None

This module is part of these learning paths


 Model data in Power BI
 Introduction to DAX10 min
 Understand context10 min
 Use the Calculate function10 min
 Use relationships effectively12 min
 Create semi-additive measures10 min
 Lab - Introduction to DAX in Power BI Desktop45 min
 Work with time intelligence10 min
 Lab - Time Intelligence and Measures in DAX45 min
 Check your knowledge5 min
 Summary3 min

Introduction to DAX
Completed100 XP
 10 minutes

Data Analysis Expressions (DAX) is a programming language that is used throughout


Microsoft Power BI for creating calculated columns, measures, and custom tables. It is a
collection of functions, operators, and constants that can be used in a formula, or expression,
to calculate and return one or more values. You can use DAX to solve a number of
calculation and data analysis problems, which can help you create new information from data
that is already in your model.

In Power BI, you can use different calculation techniques and functions to create measures or
calculated columns. Primarily, you will be able to achieve the same result by using these
techniques; however, the key is to know how and when to apply them. By having a basic
understanding of when and how to use which technique, you will be able to create robust and
high-performance data models.

By the end of this module, you'll be able to: 

 Build quick measures.


 Create calculated columns.
 Use DAX to build measures.
 Discover how context affects DAX measures.
 Use the CALCULATE function to manipulate filters.
 Implement time intelligence by using DAX.

Use calculated columns


DAX allows you to augment the data that you bring in from different data sources by creating
a calculated column that didn't originally exist in the data source. This feature should be used
sparingly, which will be explained later in this module.

For example, assume that you are importing data from a database that contains sales
transactions. Each individual sales transaction has the following columns: Order
ID, Product ID, Quantity, and Unit Price. Notice that a column doesn't exist for the total
sales amount for each order.

 Note
This module is not about data visualization, but it does show data visualization to
demonstrate how DAX works. For more information, see the learning path, Visualize data in
Power BI.  

The following figure shows how the initial shape of the data appears in a Power BI table
visual.

You can start using DAX by creating a calculated column that multiplies the unit price with
the quantity. The calculated column will create a value for each row called Total Price.
Create the new column by selecting the ellipsis (...) button on the table in the Fields list and
then selecting New column.
A new DAX formula appears in the formula bar underneath the ribbon at the top.

You can replace the "Column =" default text with the following example text:

Total Price = 'Sales OrderDetails'[Quantity] * 'Sales OrderDetails'[Unit Price]


The value on the left side of the equal sign is the column name. The text on the right side of
the equal sign is the DAX expression. This simple DAX expression takes the quantity value
and multiplies it with the unit price value for each individual row. It will produce one value
for each record in the table. If you drag the new column from the Fields list to the visual, you
will see the new values.

The previous screenshot shows that DAX is calculating correctly and displaying the results
that you wanted.

Calculated columns are materialized in the .pbix Power BI file extension, meaning that each
time you add a calculated column, you are increasing the size of the overall file. Having too
many calculated columns will slow performance and will cause you to reach the maximum
Power BI file size sooner.

Create a custom column


Three ways to create a custom column in Power BI are:

 Create the column in the source query when you get the data, for instance, by
adding the calculation to a view in a relational database.
 Create a custom column in Power Query.
 Create a calculated column by using DAX in Power BI desktop.
You can create a calculated column when you pull the data from the data source. Each data
source would have a different technique for completing this action. For instance, if you were
pulling data from a relational data source by using a view that was written in the SQL
language, it would look like the following example:

Copy
CREATE VIEW OrdersWithTotalPrice
AS
SELECT unitprice, qty, unitprice * qty as TotalPrice
FROM sales.salesorders

Using SQL language is an efficient way of creating a column because it would make the data
source do the calculations for you. In Power BI, the calculated column would appear like any
other column.

You can also use Power Query to create a custom column.

The custom column dialog uses the M language to create the new column. M language is out
of scope for the purposes of this module.

The third way to create a calculated column is by using DAX in Power BI, as previously
demonstrated.

When you create a calculated column by using DAX, you do not need to refresh the dataset to
see the new column. In the other methods, you would need a refresh to see changes. This
process can be lengthy if you are working with a lot of data. However, this issue is irrelevant
because, after columns have been created, they are rarely changed.
The DAX calculated column does not compress as well as the other methods. The other
column types do get compressed, which makes the .pbix file smaller and the performance is
usually faster.

Generally, the earlier you can create a column, the better. It is not considered an optimal
practice to use DAX for calculations if you can use a different mechanism.

In addition, one way to avoid using a calculated column is to use one of the X functions, such
as SUMX, COUNTX, MINX, and so on. The X functions are beyond the scope of this
module; however, they allow you to create measures that are aware of the data in individual
rows and calculate totals based on the totals in the row. These functions are called iterator
functions because, though they are used in measures, they iterate over the individual rows to
do their calculations. An X function will perform better and use less disk space than a
calculated column. For more information about X functions, see the Microsoft
documentation.

Use measures
Calculated columns are useful, when you are required to operate row by row. However, other
situations might require a simpler method. For example, consider a situation where you want
an aggregation that operates over the entire dataset and you want the total sales of all rows.
Furthermore, you want to slice and dice that data by other criteria like total sales by year, by
employee, or by product.

To accomplish those tasks, you would use a measure. You can build a measure without
writing DAX code; Power BI will write it for you when you create a quick measure.

Many available categories of calculations and ways to modify each calculation exist to fit
your needs. Another advantage is that you can see the DAX that's implemented by the quick
measure while jumpstarting or expanding your own DAX knowledge.

Create a quick measure


To create a quick measure in Power BI Desktop, right-click or select the ellipsis (...)
button next to any item in the Fields pane and then select New quick measure from the
menu that appears. The Quick measures screen will appear.
In the Quick measures window, you can select the calculation that you want and the fields to
run the calculation against. For instance, you can select a calculation and the column that you
want to operate over. Power BI creates the DAX measure for you and displays the DAX. This
approach can be a helpful way to learn the DAX syntax.

For more information, see the Use quick measures for common calculations documentation.

Create a measure
Measures are used in some of the most common data analyses.
To continue with the previous scenario, you want to create a measure that totals your new
column for the entire dataset. Similar to how you created a calculated column, you can go to
the Fields list, click the three-dot ellipsis on the selected field and select New measure.

Text will now appear in the formula bar underneath the ribbon.

You can replace the "Measure =" text with the following text:

Total Sales = sum('Sales OrderDetails'[Total Price])

The new measure will now appear in the Fields list.

When you drag Total Sales over to the report design surface, you will see the total sales for
the entire organization in a column chart.
Differences between a calculated column and a measure
The fundamental difference between a calculated column and a measure is that a calculated
column creates a value for each row in a table. For example, if the table has 1,000 rows, it
will have 1,000 values in the calculated column. Calculated column values are stored in the
Power BI .pbix file. Each calculated column will increase the space that is used in that file
and potentially increase the refresh time.

Measures are calculated on demand. Power BI calculates the correct value when the user
requests it. When you previously dragged the Total Sales measure onto the report, Power BI
calculated the correct total and displayed the visual. Measures do not add to the overall disk
space of the Power BI .pbix file.
Measures are calculated based on the filters that are used by the report user. These filters
combine to create the filter context.

Next unit: Understand context


Continue

Understand context
Completed100 XP
 10 minutes

How context affects DAX measures is a difficult concept to comprehend. The ensuing visuals
will demonstrate how context affects DAX measures so you can see how they interact
together.

The following three visuals use the exact same DAX measure: Total Sales.

Though each visual uses the same DAX measure and, therefore, the same DAX formula, the
visuals produce different results. For instance, the first visual shows the Total Sales measure
for the entire dataset. In this dataset, Total Sales is USD1.35 million. In the second visual,
Total Sales is broken down by year. For instance, in 2014, Total Sales is USD0.23 million. In
the third visual, Total Sales is broken down by Product ID.

With Power BI, even though the measure was only defined once, it can be used in these
visuals in different ways. Each of the totals is accurate and performs quickly. It is the context
of how the DAX measure is used that calculates these totals accurately.

Interactions between visuals will also change how the DAX measure is calculated. For
instance, if you select the second visual and then select 2015, the results appear as shown in
the following screenshot.
Selecting 2015 in the second visual changed the filter context for the DAX measure. It
modified the first visual to equal the sales for 2015: USD0.66 million. It also broke down the
Total Sales By Product ID, but only shows the results for 2015. Those calculations quickly
changed in memory and displayed the results in a highly interactive manner to the user.

The definition of the DAX measure has not changed; it's still the original, as shown in the
following example:

Total Sales = sum('Sales OrderDetails'[Total Price])

This scenario is a simple way to explain how context works with DAX. Many other factors
affect how DAX formulas are evaluated. Slicers, page filters, and more can affect how a
DAX formula is calculated and displayed.

Next unit: Use the Calculate function


Continue

Use the Calculate function


Completed100 XP
 10 minutes

The CALCULATE function in DAX is one of the most important functions that a data
analyst can learn. The function name does not adequately describe all it is intended to do.

The CALCULATE function is your method of creating a DAX measure that will override
certain portions of the context that are being used to express the correct result.

For instance, if you want to create a measure that always calculates the total sales for 2015,
regardless of which year is selected in any other visual in Power BI, you would create a
measure that looks like the following sample:

Total Sales for 2015 = CALCULATE(SUM('Sales OrderDetails'[Total Price]),


YEAR('Sales OrderDetails'[orderdate]) = 2015)
Notice how the measure is named Total Sales for 2015. When you use the CALCULATE
function to override the context, it is helpful to name the measure in a way that describes
exactly how you are overriding it. In this example, CALCULATE is aggregating the Total
Price column, just as you did in the previous measure. However, instead of operating over the
entire dataset while using whatever the filter context tells it to do, you are overriding the filter
context for the year 2015. No matter what year is selected as a filter for other reports, you
will always get the total for 2015 using this measure; all other filters still apply. The
subsequent example shows this concept in action.

When both measures are added to the previous visual they will resemble the following
screenshot.

As shown in the preceding screenshot, Total Sales is still USD1.35 million, while the 2015
Total Sales is USD0.66 million.
When you add the other visual onto the report, as you did previously, and then select 2015,
the results will look like the following image. If you select 2016, Total Sales for 2015 will
remain at USD0.66 million.

Notice how both measures are now equally the same amount. If you were to filter by any
other criteria, including region, employee, or product, the filter context would still be applied
to both measures. It's only the year filter that does not apply to that measure.

Next unit: Use relationships effectively


Continue

Use relationships effectively


Completed100 XP
 12 minutes

Another DAX function that allows you to override the default behavior is
USERELATIONSHIP.

Consider the following data model example.


The preceding screenshot shows an established relationship between
the Date and OrderDate columns, as shown by the highlighted line connecting the two. The
solid line between the two tables indicates that it is the active relationship, meaning that by
default, any slicing on the date table where measures in the Sales data are being displayed
will be along the OrderDate column. A dashed relationship exists between
the Date and ShipDate columns, indicating that it is an inactive relationship. This
relationship will never be used unless explicitly declared in a measure.

The goal is to build the following report, where you have two visuals: Sales by Ship
Date and Sales by Order Date.
These visuals show the sales over time, but the first visual is by order date and the second is
by ship date so, though they are both dates, a different data point is associated with them to
get both sets of data on the same visual.

To create this measure for Sales by Ship Date, you can use the DAX
function USERELATIONSHIP(). This function is used to specify a relationship to be used in
a specific calculation and is done without overriding any existing relationships. It is a
beneficial feature in that it allows developers to make additional calculations on inactive
relationships by overriding the default active relationship between two tables in a DAX
expression, as shown in the following example:

Sales by Ship Date = CALCULATE(Sum(Sales[TotalPrice]),


USERELATIONSHIP(Sales[ShipDate],'Calendar'[Date]))
Now, you will be able to create the second visual.

Next unit: Create semi-additive measures


Continue

Create semi-additive measures


Completed100 XP
 10 minutes

In situations where you don't want the standard evaluation behavior in Power BI, you can use
the CALCULATE and/or USERELATIONSHIP functions. However, more circumstances
exist where you don't want the standard behavior. One of those situations is when you have a
semi-additive problem to resolve. Standard measures are simple concepts, where they might
use the SUM, AVERAGE, MIN, and MAX functions. Thus far, you've been using SUM for
the Total Sales measure.

Occasionally, summing a measure doesn't make sense, such as when you are performing
inventory counts in a warehouse. For example, if on Monday, you have 100 mountain bikes,
and on Tuesday you have 125 mountain bikes, you wouldn't want to add those together to
indicate that you had 225 mountain bikes between those two days. In this circumstance, if
you want to know your stock levels for March, you would need to tell Power BI not to add
the measure but instead take the last value for the month of March and assign it to any visual.

You can use the CALCULATE function to complete this action, along with the LastDate
function, as shown in the following example:

Copy
Last Inventory Count =
CALCULATE (
SUM ( 'Warehouse'[Inventory Count] ),
LASTDATE ( 'Date'[Date] ))

This approach will stop the SUM from crossing all dates. Instead, you will only use the SUM
function on the last date of the time period, thus effectively creating a semi-additive measure.

Next unit: Lab - Introduction to DAX in Power BI


Desktop
Continue
Lab - Introduction to DAX in Power BI
Desktop
Completed100 XP

 45 minutes
This unit includes a lab to complete.

Use the free resources provided in the lab to complete the exercises in this unit. You will not
be charged.

Microsoft provides this lab experience and related content for educational purposes. All
presented information is owned by Microsoft and intended solely for learning about the
covered products and services in this Microsoft Learn module.

Launch lab

Access your environment


Before you start this lab (unless you are continuing from a previous lab), select Launch
lab above.

You are automatically logged in to your lab environment as data-ai\student.

You can now begin your work on this lab.

 Tip

To dock the lab environment so that it fills the window, select the PC icon at the top and then
select Fit Window to Machine.
In this lab, you'll create calculated tables, calculated columns, and simple measures using
Data Analysis Expressions (DAX).

In this lab, you learn how to:

 Create calculated tables


 Create calculated columns
 Create measures

Exercise 1: Create Calculated Tables


In this exercise, you'll create two calculated tables. The first will be the Salesperson table, to
allow a direct relationship between it and the Sales table. The second will be the Date table.

Open the Sales Analysis.pbix starter file, which is found in the D:\DA100\Labs\05-create-


dax-calculations-in-power-bi-desktop\Starter folder.

Task 1: Create the Salesperson table

In this task, you'll create the Salesperson table (direct relationship to Sales).

1. In Power BI Desktop, in Report view, on the Modeling ribbon, from inside


the Calculations group, select New Table.

2. In the formula bar (which opens directly beneath the ribbon when creating or
editing calculations), type Salesperson =, press Shift+Enter, type 'Salesperson
(Performance)', and then press Enter.

For your convenience, all DAX definitions in this lab can be copied from
the D:\DA100\Lab05\Assets\Snippets.txt file.

A calculated table is created by first entering the table name, followed by the
equals symbol (=), followed by a DAX formula that returns a table. The table
name can't already exist in the data model.
The formula bar supports entering a valid DAX formula. It includes features
like autocomplete, Intellisense, and color-coding, enabling you to quickly and
accurately enter the formula.

This table definition creates a copy of the Salesperson (Performance) table. It


copies the data only, however properties like visibility, formatting, etc. aren't
copied.

 Tip

You are encouraged to enter “white space” (i.e. carriage returns and tabs) to
layout formulas in an intuitive and easy-to-read format—especially when
formulas are long and complex. To enter a carriage return, press Shift+Enter.
“White space” is optional.

3. In the Fields pane, notice that the table icon has a calculator icon as well
(denoting a calculated table).

Calculated tables are defined by using a DAX formula that returns a table.
Calculated tables increase the size of the data model because they materialize
and store values. They’re recomputed whenever you refresh formula
dependencies, as will be the case in this data model when you load new (future)
date values into tables.

Unlike Power Query-sourced tables, calculated tables can't be used to load data
from external data sources. They can only transform data based on what has
already been loaded into the data model.

4. Switch to Model view.


5. Notice that the Salesperson table is available (take care, it might be hidden
from view—scroll horizontally to locate it).
6. Create a relationship from the Salesperson | EmployeeKey column to the Sales
| EmployeeKey column.
7. Right-click the inactive relationship between the Salesperson
(Performance) and Sales tables, and then select Delete.
8. When prompted to confirm the deletion, select Delete.

9. In the Salesperson table, multi-select the following columns, and then hide
them:
o EmployeeID
o EmployeeKey
o UPN
10. In the model diagram, select the Salesperson table.
11. In the Properties pane, in the Description box, enter: Salesperson related to a
sale

Recall that descriptions appear as tooltips in the Fields pane when the user


hovers their cursor over a table or field.

12. For the Salesperson (Performance) table, set the description to: Salesperson


related to region(s).

The data model now provides two alternatives when analyzing salespeople.
The Salesperson table allows you to analyze sales made by a salesperson, while
the Salesperson (Performance) table allows you to analyze sales made in the
sales region(s) assigned to the salesperson.

Task 2: Create the Date table

In this task, you'll create the Date table.

1. Switch to Data view.

2. On the Home ribbon tab, from inside the Calculations group, select New


Table.
3. In the formula bar, enter the following, and then press Enter:

DAXCopy
Date = CALENDARAUTO(6)

The CALENDARAUTO() function returns a single-column table consisting of


date values. The “auto” behavior scans all data model date columns to
determine the earliest and latest date values stored in the data model. It then
creates one row for each date within this range, extending the range in either
direction to ensure full years of data is stored.

This function can take a single optional argument, which is the last month
number of a year. When omitted, the value is 12, meaning that December is the
last month of the year. In this case 6 is entered, meaning that June is the last
month of the year.

4. Notice the column of date values.

If the column doesn’t appear, in the Fields pane, select a different table, and


then select the Date table.

The dates shown are formatted using US regional settings (that is,
mm/dd/yyyy).

5. At the bottom-left corner, in the status bar, notice the table statistics, confirming
that 1826 rows of data have been generated, which represents five full years’
data.
Task 3: Create calculated columns

In this task, you'll add additional columns to enable filtering and grouping by different time
periods. You'll also create a calculated column to control the sort order of other columns.

1. On the Table Tools contextual ribbon, from inside the Calculations group,


select New Column.

2. In the formula bar, type the following, and then press Enter:

DAXCopy
Year =

"FY" & YEAR('Date'[Date]) + IF(MONTH('Date'[Date]) > 6, 1)

A calculated column is created by first entering the column name, followed by


the equals symbol (=), followed by a DAX formula that returns a single-value
result. The column name can't already exist in the table.

The formula uses the date’s year value but adds one to the year value when the
month is after June. This is how fiscal years at Adventure Works are calculated.

3. Verify that the new column was added.

4. Use the snippets file definitions to create the following two calculated columns
for the Date table:
o Quarter
o Month
5. To validate the calculations, switch to Report view.
6. To create a new report page, at the bottom-left, select the plus icon.

7. To add a matrix visual to the new report page, in the Visualizations pane, select


the matrix visual type.

 Tip

You can hover the cursor over each icon to reveal a tooltip describing the visual
type.

8. In the Fields pane, from inside the Date table, drag the Year field into


the Rows well.
9. Drag the Month field into the Rows well, directly beneath the Year field.

10. Next to the matrix visual, select the forked-double arrow icon (which will
expand all years down one level).

11. Notice that the years expand to months, and that the months are sorted
alphabetically rather than chronologically.
By default, text values sort alphabetically, numbers sort from smallest to largest,
and dates sort from earliest to latest.

12. To customize the Month field sort order, switch to Data view.


13. Add the MonthKey column to the Date table. This formula computes a
numeric value for each year/month combination.

DAXCopy
MonthKey =

(YEAR('Date'[Date]) * 100) + MONTH('Date'[Date])

14. In Data view, verify that the new column contains numeric values (for example,
201707 for July 2017, etc.).

15. In the Fields pane, ensure that the Month field is selected (when selected, it


will have a dark gray background).
16. On the Column Tools contextual ribbon, from inside the Sort group,
select Sort by Column, and then select MonthKey.
17. In the matrix visual, notice that the months are now chronologically sorted.

Task 4: Complete the Date table

In this task, you'll complete the design of the Date table by hiding a column and creating a
hierarchy. You'll then create relationships to the Sales and Targets tables.

1. Switch to Model view.


2. In the Date table, hide the MonthKey column.
3. On the Fields right side pane, select the Date table, right click on
the Year column, and select create hierarchy.
4. Rename the newly created hierarchy to Fiscal by right click and Rename
5. Add the following two remaining field to the Fiscal hierarchy by selecting them
in the fields pane, right clicking, and selecting Add to hierarchy -> Fiscal
6. Create the follow two model relationships:
o Date | Date to Sales | OrderDate
o Date | Date to Targets | TargetMonth

7. Hide the following two columns:


o Sales | OrderDate
o Targets | TargetMonth

Task 5: Mark the Date table

In this task, you'll mark the Date table as a date table.

1. Switch to Report view.


2. In the Fields pane, select the Date table (not field).
3. On the Table Tools contextual ribbon, from inside the Calendars group,
select Mark as Date Table, and then select Mark as Date Table.

4. In the Mark as Date Table window, in the Date Column dropdown list,


select Date.
5. Select OK.

6. Save the Power BI Desktop file.

Power BI Desktop now understands that this table defines date (time). This is
important when relying on time intelligence calculations. You'll work with time
intelligence calculations in Lab 06B.

 Note

This design approach for a date table is suitable when you don’t have a date
table in your data source. If you have access to a data warehouse, it would be
appropriate to load date data from its date dimension table rather than
“redefining” date logic in your data model.

Exercise 2: Create Measures


In this exercise, you'll create and format several measures.

Task 1: Create simple measures

In this task, you'll create simple measures. Simple measures aggregate a single column or
table.

1. In Report view, on Page 2, in the Fields pane, drag the Sales | Unit Price field


into the Values section in matrix visual.
Recall that in Lab 05A, you set the Unit Price column to summarize
by Average. The result you see in the matrix visual is the monthly average unit
price.

2. In the visual fields pane (located beneath the Visualizations pane), in


the Values well, notice that Unit Price is listed.

3. Select the down-arrow for Unit Price, and then notice the available menu
options.
Visible numeric columns allow report authors to decide at report design time
how a column will summarize (or not). This can result in inappropriate
reporting. Some data modelers don’t like leaving things to chance, however, and
choose to hide these columns and instead expose aggregation logic defined by
measures. This is the approach you'll now take in this lab.

4. To create a measure, in the Fields pane, right-click the Sales table, and then


select New Measure.
5. In the formula bar, add the following measure definition:

DAXCopy
Avg Price = AVERAGE(Sales[Unit Price])

6. Add the Avg Price measure to the Values section in the matrix visual.


7. Notice that it produces the same result as the Unit Price column (but with
different formatting).
8. In the Values well, open the context menu for the Avg Price field, and notice
that it's not possible to change the aggregation technique.
9. Use the snippets file definitions to create the following five measures for
the Sales table:
o Median Price
o Min Price
o Max Price
o Orders
o Order Lines

The DISTINCTCOUNT() function used in the Orders measure will count


orders only once (ignoring duplicates). The COUNTROWS() function used in
the Order Lines measure operates over a table. In this case, the number of
orders is calculated by counting the distinct SalesOrderNumber column
values, while the number of order lines is simply the number of table rows (each
row is a line of an order).

10. Switch to Model view, and then multi-select the four price measures: Avg
Price, Max Price, Median Price, and Min Price.
11. For the multi-selection of measures, configure the following requirements:
o Set the format to two decimal places
o Assign to a display folder named Pricing

12. Hide the Unit Price column.

The Unit Price column is now not available to report authors. They must use
the measure you’ve added to the model. This design approach ensures that
report authors won’t inappropriately aggregate prices, for example, by summing
them.

13. Multi-select the Orders and Order Lines measures, and configure the


following requirements:
o Set the format use the thousands separator
o Assign to a display folder named Counts
14. In Report view, in the Values well of the matrix visual, for the Unit Price field,
select X to remove it.

15. Increase the size of the matrix visual to fill the page width and height.
16. Add the following five new measures to the matrix visual:
o Median Price
o Min Price
o Max Price
o Orders
o Order Lines

17. Verify that the results look sensible and are correctly formatted.

Task 2: Create additional measures

In this task, you'll create additional measures that use more complex expressions.

1. In Report view, select Page 1.


2. Review the table visual, noticing the total for the Target column.

Summing the target values together doesn’t make sense because salespeople
targets are set for each salesperson based on their sales region assignment(s). A
target value should only be shown when a single salesperson is filtered. You'll
implement a measure now to do just that.

3. In the table visual, remove the Target field.

4. Rename the Targets | Target column as Targets | TargetAmount.

 Tip
There are several ways to rename the column in Report view: In
the Fields pane, you can right-click the column, and then select Rename—or,
double-click the column, or press F2.

You’re about to create a measure named Target. It’s not possible to have a


column and measure in the same table, with the same name.

5. Create the following measure on the Targets table:

DAXCopy
Target =

IF(

HASONEVALUE('Salesperson (Performance)'[Salesperson]),

SUM(Targets[TargetAmount])

The HASONEVALUE() function tests whether a single value in


the Salesperson column is filtered. When true, the expression returns the sum
of target amounts (for just that salesperson). When false, BLANK is returned.

6. Format the Target measure for zero decimal places.

 Tip

You can use the Measure Tools contextual ribbon.

7. Hide the TargetAmount column.
8. Add the Target measure to the table visual.
9. Notice that the Target column total is now BLANK.
10. Use the snippets file definitions to create the following two measures for
the Targets table:
o Variance
o Variance Margin

11. Format the Variance measure for zero decimal places.


12. Format the Variance Margin measure as percentage with two decimal places.
13. Add the Variance and Variance Margin measures to the table visual.
14. Widen the table visual so all values are displayed.

While it appears all salespeople aren't meeting target, remember that the
measures aren’t yet filtered by a specific time period. You’ll produce sales
performance reports that filter by a user-selected time period in Lab 07A.

15. At the top-right corner of the Fields pane, collapse and then expand open the
pane.

Collapsing and reopening the pane resets the content.

16. Notice that the Targets table now appears at the top of the list.
Tables that comprise only visible measures are automatically listed at the top of
the list.

Finish up

In this task, you'll complete the lab.

1. Save the Power BI Desktop file.


2. Leave Power BI Desktop open.

In the next lab, you'll enhance the data model with more advanced calculations using DAX.

Next unit: Work with time intelligence


Continue

Work with time intelligence


Completed100 XP
 10 minutes

All data analysts will have to deal with time. Dates are important, so we highly recommend
that you create or import a dates table. This approach will help make date and time
calculations much simpler in DAX.

While some time calculations are simple to do in DAX, others are more difficult. For
instance, the following screenshot shows what happens if you want to display a running total.
Notice that the totals increment for each month but then reset when the year changes. In other
programming languages, this result can be fairly complicated, often involving several
variables and looping through code. DAX makes this process fairly simple, as shown in the
following example:

Copy
YTD Total Sales = TOTALYTD
(
SUM('Sales OrderDetails'[Total Price])
, Dates[Date]
)

The YTD Total Sales measure uses a built-in DAX function called TOTALYTD. This
function takes an argument for the type of calculation. You can use the SUM function to get
the Total Price, as you've done throughout this module. The second argument that you want
to operate over is the Dates field. You can use your Dates table and add this measure to your
visual, and you'll get the running total result that you're looking for. You can use all functions
with YTD, MTD, and QTD in a similar fashion.
Another example of working with time would be comparing your current sales with the sales
of a previous time period. For instance, if you want to see the total sales of the month next to
the total sales of the prior month, you would enter the DAX measure definition, as shown in
the following example:

Copy
Total Sales Previous Month = CALCULATE
(
sum('Sales OrderDetails'[Total Price])
, PREVIOUSMONTH(Dates[Date])
)

This measure uses the CALCULATE function, indicating that you're overriding the context
to evaluate this expression the way that you want to. You're summing Total Price, as you've
been doing throughout this module. For the second argument, you're using
PREVIOUSMONTH for the override, which tells Power BI that, no matter what month is the
default, the system should override it to be the previous month.

The following screenshot shows the results in a table visual.

When you examine the months side-by-side, notice that the total sales for July compare to the
total sales for June.

Next unit: Lab - Time Intelligence and Measures in DAX


Continue
Lab - Time Intelligence and Measures in
DAX
Completed100 XP

 45 minutes
This unit includes a lab to complete.

Use the free resources provided in the lab to complete the exercises in this unit. You
will not be charged.

Microsoft provides this lab experience and related content for educational purposes.
All presented information is owned by Microsoft and intended solely for learning
about the covered products and services in this Microsoft Learn module.

Launch lab

Access your environment


Before you start this lab (unless you are continuing from a previous lab),
select Launch lab above.

You are automatically logged in to your lab environment as data-ai\student.

You can now begin your work on this lab.

 Tip

To dock the lab environment so that it fills the window, select the PC icon at the top
and then select Fit Window to Machine.
In this lab, you will create measures with DAX expressions involving filter context
manipulation.

In this lab, you learn how to:

 Use the CALCULATE() function to manipulate filter context

 Use Time Intelligence functions

Exercise 1: Work with Filter Context


In this exercise, you will create measures with DAX expressions involving filter context
manipulation.

Open the lab’s starter file, which is found in the D:\DA100\Lab06B\starter folder.

Task 1: Create a matrix visual

In this task, you will create a matrix visual to support testing your new measures.

1. In Power BI Desktop, in Report view, create a new report page.

2. On Page 3, add a matrix visual.


3. Resize the matrix visual to fill the entire page.

4. To configure the matrix visual fields, from the Fields pane, drag


the Region | Regions hierarchy, and drop it inside the visual.

5. Add also the Sales | Sales field.

6. To expand the entire hierarchy, at the top-right of the matrix visual, click
the forked-double arrow icon twice.

Recall that the Regions hierarchy has the levels Group, Country,


and Region.

7. To format the visual, beneath the Visualizations pane, select


the Format pane.
8. In the Search box, enter Stepped.

9. Set the Stepped Layout property to Off.

10. Verify that the matrix visual has four column headers.
At Adventure Works, the sales regions are organized into groups,
countries, and regions. All countries—except the United States—have
just one region, which is named after the country. As the United States is
such a large sales territory, it is divided into five regions.

You’ll create several measures in this exercise, and then test them by
adding them to the matrix visual.

Task 2: Manipulate filter context

In this task, you will create several measures with DAX expressions that use the
CALCULATE() function to manipulate filter context.

1. In Report view, on the Modeling ribbon, from inside


the Calculations group, click New measure to add a measure “Sales All
Region” to the Sales table.

2. Use the following expression to create the measure:

For your convenience, all DAX definitions in this lab can be copied from
the D:\DA100\Lab06B\Assets\Snippets.txt file.
DAXCopy
Sales All Region =
CALCULATE(SUM(Sales[Sales]), REMOVEFILTERS(Region))

The CALCULATE() function is a powerful function used to manipulate the


filter context. The first argument takes an expression or a measure (a
measure is just a named expression). Subsequent arguments allow
modifying the filter context.

The REMOVEFILTERS() function removes active filters. It can take either


no arguments, or a table, a column, or multiple columns as its argument.

In this formula, the measure evaluates the sum of the Sales column in a


modified filter context, which removes any filters applied to
the Region table.

3. In the formula bar copy the expression from Snippets.txt file, and
press Enter. This create the measure in the Sales table. Review the field
list in the Fields pane under the Sales table, and you will see the Sales
All Region measure.

4. Check the Sales All Region measure in the Fields pane to add the


measure to the matrix visual.
5. Notice that the Sales All Region measure computes the total of all
region sales for each region, country (subtotal) and group (subtotal).

This measure is yet to deliver a useful result. When the sales for a group,
country, or region is divided by this value it produces a useful ratio
known as “percent of grand total”.

6. In the Fields pane, ensure that the Sales All Region measure is selected,


and then in the formula bar, replace the measure name and formula with
the following formula:

 Tip

To replace the existing formula, first copy the snippet. Then, click inside
the formula bar and press Ctrl+A to select all text. Then, press Ctrl+V to
paste the snippet to overwrite the selected text. Then press Enter.

DAXCopy
Sales % All Region =
DIVIDE(
SUM(Sales[Sales]),
CALCULATE(
SUM(Sales[Sales]),
REMOVEFILTERS(Region)
)
)

The measure has been renamed to accurately reflect the updated


formula. The DIVIDE() function divides the Sales measure (not modified
by filter context) by the Sales measure in a modified context which
removes any filters applied to the Region table.

7. In the matrix visual, notice that the measure has been renamed and that
different values now appear for each group, country, and region.

8. Format the Sales % All Region measure as a percentage with two


decimal places.

9. In the matrix visual, review the Sales % All Region measure values.

10. Add another measure to the Sales table, based on the following


expression, and format as a percentage:

DAXCopy
Sales % Country =
DIVIDE(
SUM(Sales[Sales]),
CALCULATE(
SUM(Sales[Sales]),
REMOVEFILTERS(Region[Region])
)
)

11. Notice that the Sales % Country measure formula differs slightly from


the Sales % All Region measure formula.

The difference is that the denominator modifies the filter context by


removing filters on the Region column of the Region table, not all
columns of the Region table. It means that any filters applied to the
group or country columns are preserved. It will achieve a result which
represents the sales as a percentage of country.

12. Add the Sales % Country measure to the matrix visual.

13. Notice that only the United States’ regions produce a value which is not
100%.

Recall that only the United States has multiple regions. All other
countries have a single region which explains why they are all 100%.

14. To improve the readability of this measure in visual, overwrite the Sales


% Country measure with this improved formula.

DAXCopy
Sales % Country =
IF(
ISINSCOPE(Region[Region]),
DIVIDE(
SUM(Sales[Sales]),
CALCULATE(
SUM(Sales[Sales]),
REMOVEFILTERS(Region[Region]
)
)
)

Embedded within the IF() function, the ISINSCOPE() function is used to


test whether the region column is the level in a hierarchy. When true, the
DIVIDE() function is evaluated. The absence of a false part means that
blank is returned when the region column is not in scope.
15. Notice that the Sales % Country measure now only returns a value when
a region is in scope.

16. Add another measure to the Sales table, based on the following


expression, and format as a percentage:

DAXCopy
Sales % Group =
DIVIDE(
SUM(Sales[Sales]),
CALCULATE(
SUM(Sales[Sales]),
REMOVEFILTERS(
Region[Region],
Region[Country]
)
)
)

To achieve sales as a percentage of group, two filters can be applied to


effectively remove the filters on two columns.

17. Add the Sales % Group measure to the matrix visual.

18. To improve the readability of this measure in visual, overwrite the Sales


% Group measure with this improved formula.

DAXCopy
Sales % Group =
IF(
ISINSCOPE(Region[Region])
|| ISINSCOPE(Region[Country]),
DIVIDE(
SUM(Sales[Sales]),
CALCULATE(
SUM(Sales[Sales]),
REMOVEFILTERS(
Region[Region],
Region[Country]
)
)
)
)
19. Notice that the Sales % Group measure now only returns a value when a
region or country is in scope.

20. In Model view, place the three new measures into a display folder
named Ratios.

21. Save the Power BI Desktop file.

The measures added to the Sales table have modified filter context to


achieve hierarchical navigation. Notice that the pattern to achieve the
calculation of a subtotal requires removing some columns from the filter
context, and to arrive at a grand total, all columns must be removed.

Exercise 2: Work with Time Intelligence


In this exercise, you will create a sales year-to-date (YTD) measure and sales year-
over-year (YoY) growth measure.

Task 1: Create a YTD measure

In this task, you will create a sales YTD measure.

1. In Report view, on Page 2, notice the matrix visual which displays various
measures with years and months grouped on the rows.

2. Add a measure to the Sales table, based on the following expression,


and formatted to zero decimal places:

DAXCopy
Sales YTD =
TOTALYTD(SUM(Sales[Sales]), 'Date'[Date], "6-30")

The TOTALYTD() function evaluates an expression—in this case the sum


of the Sales column—over a given date column. The date column must
belong to a date table marked as a date table. The function can also take
a third optional argument representing the last date of a year. The
absence of this date means that December 31 is the last date of the year.
For Adventure Works, June in the last month of their year, and so “6-30”
is used.

3. Add the Sales field and the Sales YTD measure to the matrix visual.

4. Notice the accumulation of sales values within the year.

The TOTALYTD() function performs filter manipulation, specifically time


filter manipulation. For example, to compute YTD sales for September
2017 (the third month of the fiscal year), all filters on the Date table are
removed and replaced with a new filter of dates commencing at the
beginning of the year (July 1, 2017) and extending through to the last
date of the in-context date period (September 30, 2017).

 Note

Many Time Intelligence functions are available in DAX to support


common time filter manipulations.

Task 2: Create a YoY growth measure

In this task, you will create a sales YoY growth measure.

1. Add an additional measure to the Sales table, based on the following


expression:

DAXCopy
Sales YoY Growth =
VAR SalesPriorYear =
CALCULATE(
SUM(Sales[Sales]),
PARALLELPERIOD(
'Date'[Date],
-12,
MONTH
)
)
RETURN
SalesPriorYear

The Sales YoY Growth measure formula declares a variable. Variables


can be useful for simplifying the formula logic, and more efficient when
an expression needs to be evaluated multiple times within the formula
(which will be the case for the YoY growth logic). Variables are declared
by a unique name, and the measure expression must then be output
after the RETURN keyword.

The SalesPriorYear variable is assigned an expression which calculates


the sum of the Sales column in a modified context that uses the
PARALLELPERIOD() function to shift 12 months back from each date in
filter context.

2. Add the Sales YoY Growth measure to the matrix visual.

3. Notice that the new measure returns blank for the first 12 months (there
were no sales recorded before fiscal year 2017).

4. Notice that the Sales YoY Growth measure value for 2017 Jul is


the Sales value for 2018 Jul.
Now that the “difficult part” of the formula has been tested, you can
overwrite the measure with the final formula which computes the growth
result.

5. To complete the measure, overwrite the Sales YoY Growth measure


with this formula, formatting it as a percentage with two decimal places:

DAXCopy
Sales YoY Growth =
VAR SalesPriorYear =
CALCULATE(
SUM(Sales[Sales]),
PARALLELPERIOD(
'Date'[Date],
-12,
MONTH
)
)
RETURN
DIVIDE(
(SUM(Sales[Sales]) - SalesPriorYear),
SalesPriorYear
)

6. In the formula, in the RETURN clause, notice that the variable is


referenced twice.

7. Verify that the YoY growth for 2018 Jul is 392.83%.


This means that July 2018 sales ($2,411,559) represents a nearly 400%
(almost 4x) improvement over the sales achieved for the prior year
($489,328).

8. In Model view, place the two new measures into a display folder
named Time Intelligence.

9. Save the Power BI Desktop file.


DAX includes many Time Intelligence functions to make it easy to
implement time filter manipulations for common business scenarios. This
exercise completes the data model development.

Exercise 3: Publish the Power BI Desktop File


In this exercise, you will publish the Power BI Desktop file to Power BI.

 Note

The following exercise will require you to login to Power BI service, you can use your
existing account or create a trial account before starting this part of the lab.

Task 1: Publish the file

In this task, you will publish the Power BI Desktop file to Power BI.

1. Save the Power BI Desktop file.

2. To publish the file, on the Home ribbon tab, from inside


the Share group, click Publish.

3. In the Publish to Power BI window, select your Sales


Analysis workspace.

4. Click Select.
5. When the file has been successfully published, click Got It.

6. Close Power BI Desktop.

7. In Edge, in the Power BI service, in the Navigation pane (located at the


left), review the contents of your Sales Analysis workspace.

The publication has added a report and a dataset. If you don’t see them,
press F5 to reload the browser, and then expand the workspace again.

The data model has been published to become a dataset. The report—
used to test your model calculations—has been added as a report. This
report is not required, so you will now delete it.

8. Hover the cursor over the Sales Analysis report, click the vertical ellipsis
(…), and then select Remove.
9. When prompted to confirm the deletion, click Delete.

Next unit: Check your knowledge

Check your knowledge


200 XP
 5 minutes

Answer the following questions to see what you've learned.


1. 

Which two functions will help you compare dates to the previous month?

CALCULATE and PREVIOUSMONTH

TOTALYTD and PREVIOUS MONTH

CALCULATE and TOTALTYD


2. 

Why would you want to override the default context?

To create measures that behave according to your intentions, regardless of what the
user selects.

To create measures that do not summarize or average.


To create new relationships.
3. 

How do you use an inactive relationship in a single measure?

Change the active relationship in the Modeling tab.

Use the USERELATIONSHIP function.

Delete one relationship.


Check your answers

Summary
Completed100 XP
 3 minutes

This module started you on a journey to understanding DAX. You learned about
creating simple DAX columns and measures, how they work, and how to choose
when to do one over the other. You learned about context and how to override it
with the CALCULATE function, and you learned about time intelligence and semi-
additive measures. Mastery of DAX will take effort and time, but this module has
provided you with a great start.

Module incomplete:
Create DAX Calculations in Power BI Desktop, Part 1

The estimated time to complete the lab is 45 minutes

In this lab you will create calculated tables, calculated columns, and simple measures using
Data Analysis Expressions (DAX).

In this lab you learn how to:

 Create calculated tables


 Create calculated columns
 Create measures
Lab story

This lab is one of many in a series of labs that was designed as a complete story from data
preparation to publication as reports and dashboards. You can complete the labs in any order.
However, if you intend to work through multiple labs, for the first 10 labs, we suggest you do
them in the following order:

1. Prepare Data in Power BI Desktop


2. Load Data in Power BI Desktop
3. Model Data in Power BI Desktop, Part 1
4. Model Data in Power BI Desktop, Part 2
5. Create DAX Calculations in Power BI Desktop, Part 1
6. Create DAX Calculations in Power BI Desktop, Part 2
7. Design a Report in Power BI Desktop, Part 1
8. Design a Report in Power BI Desktop, Part 2
9. Create a Power BI Dashboard
10. Create a Power BI Paginated Report
11. Perform Data Analysis in Power BI Desktop
12. Enforce Row-Level Security

Exercise 1: Create Calculated Tables


In this exercise you will create two calculated tables. The first will be the Salesperson table,
to allow a direct relationship between it and the Sales table. The second will be
the Date table.

Task 1: Get started

In this task you will setup the environment for the lab.

Important: If you are continuing on from the previous lab (and you completed that lab
successfully), do not complete this task; instead, continue from the next task.

1. To open the Power BI Desktop, on the taskbar, click the Microsoft Power BI Desktop
shortcut.

2. To close the getting started window, at the top-left of the window, click X.

3. To open the starter Power BI Desktop file, click the File ribbon tab to open the
backstage view.
4. Select Open Report.

5. Click Browse Reports.

6. In the Open window, navigate to the D:\DA100\Labs\05-create-dax-calculations-


in-power-bi-desktop\Starter folder.
7. Select the Sales Analysis file.
8. Click Open.

9. Close any informational windows that may open.


10. To create a copy of the file, click the File ribbon tab to open the backstage view.
11. Select Save As.

12. If prompted to apply changes, click Apply.


13. In the Save As window, navigate to the D:\DA100\MySolution folder.
14. Click Save.

Task 2: Create the Salesperson table

In this task you will create the Salesperson table (direct relationship to Sales).

1. In Power BI Desktop, in Report view, on the Modeling ribbon, from inside


the Calculations group, click New Table.

2. In the formula bar (which opens directly beneath the ribbon when creating or editing
calculations), type Salesperson =, press Shift+Enter, type 'Salesperson
(Performance)', and then press Enter.

For your convenience, all DAX definitions in this lab can be copied from the snippets
file, located in  D:\DA100\Labs\05-create-dax-calculations-in-power-bi-desktop\
Assets\Snippets.txt.

A calculated table is created by first entering the table name, followed by the equals
symbol (=), followed by a DAX formula that returns a table. Note that the table name
cannot already exist in the data model.

The formula bar supports entering a valid DAX formula. It includes features like
auto-complete, Intellisense and color-coding, enabling you to quickly and accurately
enter the formula.

This table definition creates a copy of the Salesperson (Performance) table. It copies


the data only, however model properties like visibility, formatting, etc. are not copied.
Tip: You’re encouraged to enter “white space” (i.e. carriage returns and tabs) to
layout formulas in an intuitive and easy-to-read format—especially when formulas
are long and complex. To enter a carriage return, press Shift+Enter. “White space”
is optional.

3. In the Fields pane, notice that the table icon is a shade of blue (denoting a calculated
table).

Calculated tables are defined by using a DAX formula which returns a table. It’s
important to understand that calculated tables increase the size of the data model
because they materialize and store values. They’re recomputed whenever formula
dependencies are refreshed, as will be the case for this data model when new (future)
date values are loaded into tables.

Unlike Power Query-sourced tables, calculated tables can’t be used to load data
from external data sources. They can only transform data based on what has already
been loaded into the data model.

4. Switch to Model view.


5. Notice that the Salesperson table is available (take care, it might be hidden from
view, in which case scroll horizontally to locate it).
6. Create a relationship from the Salesperson | EmployeeKey column to the Sales |
EmployeeKey column.
7. Right-click the inactive relationship between the Salesperson
(Performance) and Sales tables, and then select Delete.
8. When prompted to confirm the deletion, click Delete.

9. In the Salesperson table, multi-select the following columns, and then hide them (set
the Is Hidden property to Yes):
o EmployeeID
o EmployeeKey
o UPN
10. In the model diagram, select the Salesperson table.
11. In the Properties pane, in the Description box, enter: Salesperson related to Sales

You may recall that descriptions appear as tooltips in the Fields pane when the user
hovers their cursor over a table or field.

12. For the Salesperson (Performance) table, set the description to: Salesperson related


to region(s)

The data model now provides two alternatives when analyzing salespeople.
The  Salesperson  table allows analyzing sales made by a salesperson, while
the Salesperson (Performance)  table allows analyzing sales made in the sales
region(s) assigned to the salesperson.

Task 3: Create the Date table

In this task you will create the Date table.

1. Switch to Data view.

2. On the Home ribbon tab, from inside the Calculations group, click New Table.


3. In the formula bar, enter the following:

DAX

Date =
CALENDARAUTO(6)

The CALENDARAUTO() function returns a single-column table consisting of date


values. The “auto” behavior scans all data model date columns to determine the
earliest and latest date values stored in the data model. It then creates one row for
each date within this range, extending the range in either direction to ensure full
years of data is stored.

This function can take a single optional argument that is the last month number of a
year. When omitted, the value is 12, meaning that December is the last month of the
year. In this case, 6 is entered, meaning that June is the last month of the year.

4. Notice the column of date values.

The dates shown are formatted using US regional settings (i.e. mm/dd/yyyy).

5. At the bottom-left corner, in the status bar, notice the table statistics, confirming that
1826 rows of data have been generated, which represents five full years’ data.

Task 4: Create calculated columns

In this task you will add additional columns to enable filtering and grouping by different time
periods. You will also create a calculated column to control the sort order of other columns.

For your convenience, all DAX definitions in this lab can be copied from the snippets file,
located in D:\DA100\Labs\05-create-dax-calculations-in-power-bi-desktop\Assets\
Snippets.txt.

1. On the Table Tools contextual ribbon, from inside the Calculations group, click New


Column.
2. In the formula bar, type the following (or copy from the snippets file), and then
press Enter:

DAX

Year =
"FY" & YEAR('Date'[Date]) + IF(MONTH('Date'[Date]) > 6, 1)

A calculated column is created by first entering the column name, followed by the
equals symbol (=), followed by a DAX formula that returns a single-value result. The
column name cannot already exist in the table.

The formula uses the date’s year value but adds one to the year value when the month
is after June. It’s how fiscal years at Adventure Works are calculated.

3. Verify that the new column was added.

4. Use the snippets file definitions to create the following two calculated columns for
the Date table:
o Quarter
o Month
5. To validate the calculations, switch to Report view.
6. To create a new report page, at the bottom-left, click the plus icon.

7. To add a matrix visual to the new report page, in the Visualizations pane, select the
matrix visual type.

Tip: You can hover the cursor over each icon to reveal a tooltip describing the visual
type.

8. In the Fields pane, from inside the Date table, drag the Year field into


the Rows well/area.
9. Drag the Month field into the Rows well/area, directly beneath the Year field.

10. At the top-right of the matrix visual (or bottom, depending on the location of the
visual), click the forked-double arrow icon (which will expand all years down one
level).

11. Notice that the years expand to months, and that the months are sorted alphabetically
rather than chronologically.
By default, text values sort alphabetically, numbers sort from smallest to largest, and
dates sort from earliest to latest.

12. To customize the Month field sort order, switch to Data view.


13. Add the MonthKey column to the Date table.

DAX

MonthKey =
(YEAR('Date'[Date]) * 100) + MONTH('Date'[Date])

This formula computes a numeric value for each year/month combination.

14. In Data view, verify that the new column contains numeric values (e.g. 201707 for
July 2017, etc.).

15. Switch back to Report view.


16. In the Fields pane, ensure that the Month field is selected (when selected, it will have
a dark gray background).
17. On the Column Tools contextual ribbon, from inside the Sort group, click Sort by
Column, and then select MonthKey.
18. In the matrix visual, notice that the months are now chronologically sorted.

Task 5: Complete the Date table

In this task you will complete the design of the Date table by hiding a column and creating a
hierarchy. You will then create relationships to the Sales and Targets tables.

1. Switch to Model view.


2. In the Date table, hide the MonthKey column (set Is Hidden to Yes).
3. On the Fields right side pane, select the Date table, right click on the Year column,
and select create hierarchy.
4. Rename newly created hierarchy to Fiscal by right click and Rename.
5. Add the follow two remaining fields to the Fiscal hierachy by selecting them in the
fields pane, right clicking, selecting Add to hierarchy -> Fiscal.
o Quarter
o Month
6. Create the following two model relationships:
o Date | Date to Sales | OrderDate
o Date | Date to Targets | TargetMonth
7. Hide the following two columns:
o Sales | OrderDate
o Targets | TargetMonth

Task 6: Mark the Date table

In this task you will mark the Date table as a date table.

1. Switch to Report view.


2. In the Fields pane, select the Date table (not the Date field).
3. On the Table Tools contextual ribbon, from inside the Calendars group, click Mark
as Date Table, and then select Mark as Date Table.
4. In the Mark as Date Table window, in the Date Column dropdown list, select Date.

5. Click OK.

6. Save the Power BI Desktop file.

Power BI Desktop now understands that this table defines date (time). It’s important
when relying on time intelligence calculations. You’ll work with time intelligence
calculations in the Create DAX Calculations in Power BI Desktop, Part 2 lab.

Note that this design approach for a date table is suitable when you don’t have a date
table in your data source. If you have a data warehouse, it would be appropriate to
load date data from its date dimension table rather than “redefining” date logic in
your data model.

Exercise 2: Create Measures


In this exercise you will create and format several measures.
Task 1: Create simple measures

In this task you will create simple measures. Simple measures aggregate values in a single
column or count rows of a table.

1. In Report view, on Page 2, in the Fields pane, drag the Sales | Unit Price field into


the matrix visual.

The labs use a shorthand notation to reference a field. It will look like this: Sales |
Unit Price. In this example, Sales is the table name and Unit Price is the field name.

You may recall that in the Model Data in Power BI Desktop, Part 2 lab, you set
the Unit Price column to summarize by Average. The result you see in the matrix
visual is the monthly average unit price (sum of unit price values divided by the count
of unit prices).

2. In the visual fields pane (located beneath the Visualizations pane), in the Values field


well/area, notice that Unit Price is listed.

3. Click the down-arrow for Unit Price, and then notice the available menu options.
Visible numeric columns allow report authors at report design time to decide how
column values will summarize (or not). It can result in inappropriate reporting. Some
data modelers don’t like leaving things to chance, however, and choose to hide these
columns and instead expose aggregation logic defined in measures. It’s the approach
you will now take in this lab.

4. To create a measure, in the Fields pane, right-click the Sales table, and then


select New Measure.
5. In the formula bar, add the following measure definition:

DAX

Avg Price =
AVERAGE(Sales[Unit Price])

6. Add the Avg Price measure to the matrix visual.


7. Notice that it produces the same result as the Unit Price column (but with different
formatting).
8. In the Values well, open the context menu for the Avg Price field, and notice that it is
not possible to change the aggregation technique.
It’s not possible to modify the aggregation behavior of a measure.

9. Use the snippets file definitions to create the following five measures for
the Sales table:
o Median Price
o Min Price
o Max Price
o Orders
o Order Lines

The DISTINCTCOUNT() function used in the Orders measure will count orders only


once (ignoring duplicates). The COUNTROWS() function used in the Order
Lines measure operates over a table.

In this case, the number of orders is calculated by counting the


distinct SalesOrderNumber  column values, while the number of order lines is simply
the number of table rows (each row is a line of an order).

10. Switch to Model view, and then multi-select the four price measures: Avg Price, Max
Price, Median Price, and Min Price.
11. For the multi-selection of measures, configure the following requirements:
o Set the format to two decimal places
o Assign to a display folder named Pricing
12. Hide the Unit Price column.

The  Unit Price column is now not available to report authors. They must use the
pricing measures you’ve added to the model. This design approach ensures that
report authors won’t inappropriately aggregate prices, for example, by summing
them.

13. Multi-select the Order Lines and Orders measures, and then configure the following


requirements:
o Set the format use the thousands separator
o Assign to a display folder named Counts
14. In Report view, in the Values well/area of the matrix visual, for the Unit Price field,
click X to remove it.

15. Increase the size of the matrix visual to fill the page width and height.
16. Add the following five measures to the matrix visual:
o Median Price
o Min Price
o Max Price
o Orders
o Order Lines
17. Verify that the results looks sensible and are correctly formatted.

Task 2: Create additional measures

In this task you will create additional measures that use more complex formulas.

1. In Report view, select Page 1.


2. Review the table visual, noticing the total for the Target column.

You may recall from a previous lab that there’s a many-to-many relationship between
salespeople and regions. This means that summing the target values together doesn’t
make sense because salespeople targets are set for each salesperson based on their
sales region assignment(s). A target value should only be shown when a single
salesperson is filtered. You’ll now implement a measure now to do just that.

3. Select the table visual, and then in the Visualizations pane, remove the Target field.

4. Rename the Targets | Target column as Targets | TargetAmount.

Tip: There are several ways to rename the column in Report view: In
the Fields pane, you can right-click the column, and then select Rename—or,
double-click the column, or press  F2.
You’re about to create a measure named Target. It’s not possible to have a column
and measure in the same table with the same name.

5. Create the following measure on the Targets table:

DAX

Target =

IF(

HASONEVALUE('Salesperson (Performance)'[Salesperson]),

SUM(Targets[TargetAmount])

The HASONEVALUE() function tests whether a single value in


the Salesperson column is filtered. When true, the expression returns the sum of
target amounts (for just that salesperson). When false, BLANK is returned.

6. Format the Target measure for zero decimal places.

Tip: You can use the Measure Tools contextual ribbon.

7. Hide the TargetAmount column.

Tip: You can right-click the column in the Fields pane, and then select Hide.

8. Add the Target measure to the table visual.


9. Notice that the Target column total is now BLANK.

10. Use the snippets file definitions to create the following two measures for
the Targets table:
o Variance
o Variance Margin
11. Format the Variance measure for zero decimal places.
12. Format the Variance Margin measure as percentage with two decimal places.
13. Add the Variance and Variance Margin measures to the table visual.
14. Resize the table visual so all columns and rows can be seen.

While it appears all salespeople are not meeting target, remember that the table
visual isn’t yet filtered by a specific time period. You’ll produce sales performance
reports that filter by a user-selected time period in the Design a Report in Power BI
Desktop, Part 1 lab.

15. At the top-right corner of the Fields pane, collapse and then expand open the pane.

Collapsing and re-opening the pane resets the content.

16. Notice that the Targets table now appears at the top of the list.
Tables that comprise only visible measures are automatically listed at the top of the
list.

Task 3: Finish up

In this task you will complete the lab.

1. Save the Power BI Desktop file.


2. If you intend to start the next lab, leave Power BI Desktop open.

You’ll enhance the data model with more advanced calculations using DAX in
the Create DAX Calculations in Power BI Desktop, Part 2 lab.

Congratulations!

Create DAX Calculations in Power BI Desktop, Part 2


The estimated time to complete the lab is 45 minutes

In this lab you will create measures with DAX expressions involving filter context
manipulation.

In this lab you learn how to:

 Use the CALCULATE() function to manipulate filter context


 Use Time Intelligence functions

Lab story

This lab is one of many in a series of labs that was designed as a complete story from data
preparation to publication as reports and dashboards. You can complete the labs in any order.
However, if you intend to work through multiple labs, for the first 10 labs, we suggest you do
them in the following order:

1. Prepare Data in Power BI Desktop


2. Load Data in Power BI Desktop
3. Model Data in Power BI Desktop, Part 1
4. Model Data in Power BI Desktop, Part 2
5. Create DAX Calculations in Power BI Desktop, Part 1
6. Create DAX Calculations in Power BI Desktop, Part 2
7. Design a Report in Power BI Desktop, Part 1
8. Design a Report in Power BI Desktop, Part 2
9. Create a Power BI Dashboard
10. Create a Power BI Paginated Report
11. Perform Data Analysis in Power BI Desktop
12. Enforce Row-Level Security

Exercise 1: Work with Filter Context


In this exercise you will create measures with DAX expressions involving filter context
manipulation.

Task 1: Get started

In this task you will setup the environment for the lab.

Important: If you are continuing on from the previous lab (and you completed that lab
successfully), do not complete this task; instead, continue from the next task.

1. To open the Power BI Desktop, on the taskbar, click the Microsoft Power BI Desktop
shortcut.
2. To close the getting started window, at the top-left of the window, click X.

3. To open the starter Power BI Desktop file, click the File ribbon tab to open the
backstage view.
4. Select Open Report.

5. Click Browse Reports.

6. In the Open window, navigate to the D:\DA100\Labs\06-create-dax-calculations-


in-power-bi-desktop-advanced\Starter folder.
7. Select the Sales Analysis file.
8. Click Open.

9. Close any informational windows that may open.


10. To create a copy of the file, click the File ribbon tab to open the backstage view.
11. Select Save As.
12. If prompted to apply changes, click Apply.

13. In the Save As window, navigate to the D:\DA100\MySolution folder.


14. Click Save.

Task 2: Create a matrix visual

In this task you will create a matrix visual to support testing your new measures.

1. In Power BI Desktop, in Report view, create a new report page.

2. On Page 3, add a matrix visual.


3. Resize the matrix visual to fill the entire page.
4. To configure the matrix visual fields, from the Fields pane, drag the Region |
Regions hierarchy, and drop it inside the visual.

The labs use a shorthand notation to reference a field or hierarchy. It will look like
this: Region | Regions. In this example,  Region  is the table name and Regions is the
hierarchy name.

5. Add also the Sales | Sales field.


6. To expand the entire hierarchy, at the top-right of the matrix visual, click the forked-
double arrow icon twice.

You may recall that the  Regions hierarchy has the levels Group, Country,


and  Region.

7. To format the visual, beneath the Visualizations pane, select the Format pane.

8. In the Search box, enter Stepped.
9. Set the Stepped Layout property to Off.

10. Verify that the matrix visual now has four column headers.

At Adventure Works, the sales regions are organized into groups, countries, and
regions. All countries—except the United States—have just one region, which is
named after the country. As the United States is such a large sales territory, it’s
divided into five sales regions.

You’ll create several measures in this exercise, and then test them by adding them to
the matrix visual.
Task 3: Manipulate filter context

In this task you will create several measures with DAX expressions that use the
CALCULATE() function to manipulate filter context.

1. Add a measure to the Sales table, based on the following expression:

For your convenience, all DAX definitions in this lab can be copied from the D:\
DA100\Labs\06-create-dax-calculations-in-power-bi-desktop-advanced\Assets\
Snippets.txt file.

DAX

Sales All Region =

CALCULATE(SUM(Sales[Sales]), REMOVEFILTERS(Region))

The CALCULATE() function is a powerful function used to manipulate the filter


context. The first argument takes an expression or a measure (a measure is just a
named expression). Subsequent arguments allow modifying the filter context.

The REMOVEFILTERS() function removes active filters. It can take either no


arguments, or a table, a column, or multiple columns as its argument.

In this formula, the measure evaluates the sum of the Sales column in a modified


filter context, which removes any filters applied to the columns of the Region table.

2. Add the Sales All Region measure to the matrix visual.


3. Notice that the Sales All Region measure computes the total of all region sales for
each region, country (subtotal) and group (subtotal).

The new measure is yet to deliver a useful result. When the sales for a group, country,
or region is divided by this value it will produce a useful ratio known as “percent of
grand total”.

4. In the Fields pane, ensure that the Sales All Region measure is selected (when


selected, it will have a dark gray background), and then in the formula bar, replace the
measure name and formula with the following formula:

Tip: To replace the existing formula, first copy the snippet. Then, click inside the
formula bar and press  Ctrl+A to select all text. Then, press Ctrl+V  to paste the
snippet to overwrite the selected text. Then press Enter.

DAX

Sales % All Region =


DIVIDE(
SUM(Sales[Sales]),
CALCULATE(
SUM(Sales[Sales]),
REMOVEFILTERS(Region)
)
)
The measure has been renamed to accurately reflect the updated formula. The
DIVIDE() function divides the Sales measure (not modified by filter context) by
the Sales measure in a modified context, which removes any filters applied to
the Region table.

5. In the matrix visual, notice that the measure has been renamed and that a different
values now appear for each group, country, and region.
6. Format the Sales % All Region measure as a percentage with two decimal places.
7. In the matrix visual, review the Sales % All Region measure values.

8. Add another measure to the Sales table, based on the following expression, and


format as a percentage:

DAX

Sales % Country =
DIVIDE(
SUM(Sales[Sales]),
CALCULATE(
SUM(Sales[Sales]),
REMOVEFILTERS(Region[Region])
)
)

9. Notice that the Sales % Country measure formula differs slightly from the Sales %


All Region measure formula.

The difference is that the denominator modifies the filter context by removing filters
on the Region column of the  Region table, not all columns of the Region table. It
means that any filters applied to the group or country columns are preserved. It’ll
achieve a result that represents the sales as a percentage of country.

10. Add the Sales % Country measure to the matrix visual.


11. Notice that only the United States’ regions produce a value which is not 100%.
You may recall that only the United States has multiple regions. All other countries
comprise a single region, which explains why they are all 100%.

12. To improve the readability of this measure in visual, overwrite the Sales %


Country measure with this improved formula.

DAX

Sales % Country =
IF(
ISINSCOPE(Region[Region]),
DIVIDE(
SUM(Sales[Sales]),
CALCULATE(
SUM(Sales[Sales]),
REMOVEFILTERS(Region[Region])
)
)
)

Embedded within the IF() function, the ISINSCOPE() function is used to test whether
the region column is the level in a hierarchy of levels. When true, the DIVIDE()
function is evaluated. The absence of a false part means that blank is returned when
the region column is not in scope.

13. Notice that the Sales % Country measure now only returns a value when a region is
in scope.

14. Add another measure to the Sales table, based on the following expression, and
format as a percentage:

DAX

Sales % Group =
DIVIDE(
SUM(Sales[Sales]),
CALCULATE(
SUM(Sales[Sales]),
REMOVEFILTERS(
Region[Region],
Region[Country]
)
)
)

To achieve sales as a percentage of group, two filters can be applied to effectively


remove the filters on two columns.

15. Add the Sales % Group measure to the matrix visual.


16. To improve the readability of this measure in visual, overwrite the Sales %
Group measure with this improved formula.

DAX

Sales % Group =
IF(
ISINSCOPE(Region[Region])
|| ISINSCOPE(Region[Country]),
DIVIDE(
SUM(Sales[Sales]),
CALCULATE(
SUM(Sales[Sales]),
REMOVEFILTERS(
Region[Region],
Region[Country]
)
)
)
)

17. Notice that the Sales % Group measure now only returns a value when a region or
country is in scope.
18. In Model view, place the three new measures into a display folder named Ratios.

19. Save the Power BI Desktop file.

The measures added to the Sales  table have modified filter context to achieve
hierarchical navigation. Notice that the pattern to achieve the calculation of a
subtotal requires removing some columns from the filter context, and to arrive at a
grand total, all columns must be removed.

Exercise 2: Work with Time Intelligence


In this exercise you will create a sales year-to-date (YTD) measure and sales year-over-year
(YoY) growth measure.

Task 1: Create a YTD measure

In this task you will create a sales YTD measure.

1. In Report view, on Page 2, notice the matrix visual that displays various measures
with years and months grouped on the rows.
2. Add a measure to the Sales table, based on the following expression, and formatted to
zero decimal places:

DAX

Sales YTD =
TOTALYTD(SUM(Sales[Sales]), 'Date'[Date], "6-30")

The TOTALYTD() function evaluates an expression—in this case the sum of


the Sales column—over a given date column. The date column must belong to a date
table marked as a date table, as was done in the Create DAX Calculations in Power
BI Desktop, Part 1  lab.

The function can also take a third optional argument representing the last date of a
year. The absence of this date means that December 31 is the last date of the year.
For Adventure Works, June in the last month of their year, and so “6-30” is used.

3. Add the Sales field and the Sales YTD measure to the matrix visual.


4. Notice the accumulation of sales values within the year.
The TOTALYTD() function performs filter manipulation, specifically time filter
manipulation. For example, to compute YTD sales for September 2017 (the third
month of the fiscal year), all filters on the Date table are removed and replaced with
a new filter of dates commencing at the beginning of the year (July 1, 2017) and
extending through to the last date of the in-context date period (September 30, 2017).

Note that many Time Intelligence functions are available in DAX to support common
time filter manipulations.

Task 2: Create a YoY growth measure

In this task you will create a sales YoY growth measure.

1. Add an additional measure to the Sales table, based on the following expression:

DAX

Sales YoY Growth =


VAR SalesPriorYear =
CALCULATE(
SUM(Sales[Sales]),
PARALLELPERIOD(
'Date'[Date],
-12,
MONTH
)
)
RETURN
SalesPriorYear

The  Sales YoY Growth measure formula declares a variable. Variables can be useful
for simplifying the formula logic, and more efficient when an expression needs to be
evaluated multiple times within the formula (which will be the case for the YoY
growth logic). Variables are declared by a unique name, and the measure expression
must then be output after the RETURN keyword.

The  SalesPriorYear  variable is assigned an expression which calculates the sum of


the Sales column in a modified context that uses the PARALLELPERIOD() function
to shift 12 months back from each date in filter context.

2. Add the Sales YoY Growth measure to the matrix visual.


3. Notice that the new measure returns BLANK for the first 12 months (because there
were no sales recorded before fiscal year 2017).
4. Notice that the Sales YoY Growth measure value for 2018 Jul is the Sales value
for 2017 Jul.
Now that the “difficult part” of the formula has been tested, you can overwrite the
measure with the final formula which computes the growth result.

5. To complete the measure, overwrite the Sales YoY Growth measure with this


formula, formatting it as a percentage with two decimal places:

DAX

Sales YoY Growth =


VAR SalesPriorYear =
CALCULATE(
SUM(Sales[Sales]),
PARALLELPERIOD(
'Date'[Date],
-12,
MONTH
)
)
RETURN
DIVIDE(
(SUM(Sales[Sales]) - SalesPriorYear),
SalesPriorYear
)

6. In the formula, in the RETURN clause, notice that the variable is referenced twice.


7. Verify that the YoY growth for 2018 Jul is 392.83%.
It means that July 2018 sales ($2,411,559) represents a nearly 400% (almost 4x)
improvement over the sales achieved at the same time of the prior year ($489,328).

8. In Model view, place the two new measures into a display folder named Time
Intelligence.

Task 3: Finish up

In this task you will complete the lab.

1. To clean up the solution ready for report development, at the bottom-left, right-click
the Page 2 tab, and then select Delete page.

2. When prompted to delete the page, click Delete.


3. Delete Page 3 also.
4. On the remaining page, to clear the page, select the table visual, and the press
the Delete key.
5. Save the Power BI Desktop file.
6. If you intend to start the next lab, leave Power BI Desktop open.

You’ll create a report based on the data model in the Design a Report in Power BI
Desktop, Part 1 lab.

Congratulations!

You have successfully completed this Module, to mark the lab as complete click End.

You might also like