6 Introduction To Creating Measures Using DAX in Power BI
6 Introduction To Creating Measures Using DAX in Power BI
6 Introduction To Creating Measures Using DAX in Power BI
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
Introduction to DAX
Completed100 XP
10 minutes
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.
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:
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 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.
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.
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:
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.
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:
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.
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:
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.
Another DAX function that allows you to override the default behavior is
USERELATIONSHIP.
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:
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.
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
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).
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.
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.
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
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.
DAXCopy
Date = CALENDARAUTO(6)
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.
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.
DAXCopy
Year =
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.
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.
Tip
You can hover the cursor over each icon to reveal a tooltip describing the visual
type.
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.
DAXCopy
MonthKey =
14. In Data view, verify that the new column contains numeric values (for example,
201707 for July 2017, etc.).
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.
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.
In this task, you'll create simple measures. Simple measures aggregate a single column or
table.
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.
DAXCopy
Avg Price = AVERAGE(Sales[Unit Price])
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
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.
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.
In this task, you'll create additional measures that use more complex expressions.
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.
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.
DAXCopy
Target =
IF(
HASONEVALUE('Salesperson (Performance)'[Salesperson]),
SUM(Targets[TargetAmount])
Tip
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
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.
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 the next lab, you'll enhance the data model with more advanced calculations using DAX.
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.
When you examine the months side-by-side, notice that the total sales for July compare to the
total sales for June.
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
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 task, you will create a matrix visual to support testing your new measures.
6. To expand the entire hierarchy, at the top-right of the matrix visual, click
the forked-double arrow icon twice.
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.
In this task, you will create several measures with DAX expressions that use the
CALCULATE() function to manipulate filter context.
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))
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.
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”.
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)
)
)
7. In the matrix visual, notice that the measure has been renamed and that
different values now appear for each group, country, and region.
DAXCopy
Sales % Country =
DIVIDE(
SUM(Sales[Sales]),
CALCULATE(
SUM(Sales[Sales]),
REMOVEFILTERS(Region[Region])
)
)
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%.
DAXCopy
Sales % Country =
IF(
ISINSCOPE(Region[Region]),
DIVIDE(
SUM(Sales[Sales]),
CALCULATE(
SUM(Sales[Sales]),
REMOVEFILTERS(Region[Region]
)
)
)
DAXCopy
Sales % Group =
DIVIDE(
SUM(Sales[Sales]),
CALCULATE(
SUM(Sales[Sales]),
REMOVEFILTERS(
Region[Region],
Region[Country]
)
)
)
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.
1. In Report view, on Page 2, notice the matrix visual which displays various
measures with years and months grouped on the rows.
DAXCopy
Sales YTD =
TOTALYTD(SUM(Sales[Sales]), 'Date'[Date], "6-30")
Note
DAXCopy
Sales YoY Growth =
VAR SalesPriorYear =
CALCULATE(
SUM(Sales[Sales]),
PARALLELPERIOD(
'Date'[Date],
-12,
MONTH
)
)
RETURN
SalesPriorYear
3. Notice that the new measure returns blank for the first 12 months (there
were no sales recorded before fiscal year 2017).
DAXCopy
Sales YoY Growth =
VAR SalesPriorYear =
CALCULATE(
SUM(Sales[Sales]),
PARALLELPERIOD(
'Date'[Date],
-12,
MONTH
)
)
RETURN
DIVIDE(
(SUM(Sales[Sales]) - SalesPriorYear),
SalesPriorYear
)
8. In Model view, place the two new measures into a display folder
named Time Intelligence.
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.
In this task, you will publish the Power BI Desktop file to Power BI.
4. Click Select.
5. When the file has been successfully published, click Got It.
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.
Which two functions will help you compare dates to the previous month?
To create measures that behave according to your intentions, regardless of what the
user selects.
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
In this lab you will create calculated tables, calculated columns, and simple measures using
Data Analysis Expressions (DAX).
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:
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.
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.
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.
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.
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.
DAX
Date =
CALENDARAUTO(6)
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.
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.
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.
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.
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.
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.
DAX
MonthKey =
(YEAR('Date'[Date]) * 100) + MONTH('Date'[Date])
14. In Data view, verify that the new column contains numeric values (e.g. 201707 for
July 2017, etc.).
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.
5. Click OK.
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.
In this task you will create simple measures. Simple measures aggregate values in a single
column or count rows of a table.
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).
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.
DAX
Avg Price =
AVERAGE(Sales[Unit Price])
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
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.
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.
In this task you will create additional measures that use more complex formulas.
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.
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.
DAX
Target =
IF(
HASONEVALUE('Salesperson (Performance)'[Salesperson]),
SUM(Targets[TargetAmount])
7. Hide the TargetAmount column.
Tip: You can right-click the column in the Fields pane, and then select Hide.
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.
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
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!
In this lab you will create measures with DAX expressions involving filter context
manipulation.
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:
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.
In this task you will create a matrix visual to support testing your new measures.
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.
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.
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
CALCULATE(SUM(Sales[Sales]), REMOVEFILTERS(Region))
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”.
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
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.
DAX
Sales % Country =
DIVIDE(
SUM(Sales[Sales]),
CALCULATE(
SUM(Sales[Sales]),
REMOVEFILTERS(Region[Region])
)
)
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.
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]
)
)
)
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.
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.
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 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.
Note that many Time Intelligence functions are available in DAX to support common
time filter manipulations.
DAX
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.
DAX
8. In Model view, place the two new measures into a display folder named Time
Intelligence.
Task 3: Finish up
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.
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.