Lab - Introduction to DAX in Power BI Desktop
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.
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 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
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.
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 will create the Salesperson table (direct relationship to Sales).
In Power BI Desktop, in Report view, on the Modeling ribbon, from inside the Calculations group, click New Table.
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\Lab06A\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 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 properties like visibility, formatting, etc. are not copied.
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.
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 which returns a table. It is important to understand that calculated tables increase the size of the data model because they materialize and store values. They are recomputed whenever formula dependencies are refreshed, as will be the case in this data model when new (future) date values are loaded into tables.
Unlike Power Query-sourced tables, calculated tables cannot 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.
Switch to Model view.
Notice that the Salesperson table is available (take care, it might be hidden from view—scroll horizontally to locate it).
Create a relationship from the Salesperson | EmployeeKey column to the Sales | EmployeeKey column.
Right-click the inactive relationship between the Salesperson (Performance) and Sales tables, and then select Delete.
When prompted to confirm the deletion, click Delete.
In the Salesperson table, multi-select the following columns, and then hide them:
In the diagram, select the Salesperson table.
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.
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 will create the Date table.
Switch to Data view.
On the Home ribbon tab, from inside the Calculations group, click New Table.
In the formula bar, enter the following, and then press Enter:
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.
Notice the column of date values.
If the column does not appear, in the Fields pane, select a different table, and then select the Date table.
The dates shown are formatted using US regional settings (i.e. mm/dd/yyyy).
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 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.
On the Table Tools contextual ribbon, from inside the Calculations group, click New Column.
In the formula bar, type the following, and then press Enter:
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. This is how fiscal years at Adventure Works are calculated.
Verify that the new column was added.
Use the snippets file definitions to create the following two calculated columns for the Date table:
To validate the calculations, switch to Report view.
To create a new report page, at the bottom-left, click the plus icon.
To add a matrix visual to the new report page, in the Visualizations pane, select the matrix visual type.
You can hover the cursor over each icon to reveal a tooltip describing the visual type.
In the Fields pane, from inside the Date table, drag the Year field into the Rows well.
Drag the Month field into the Rows well, directly beneath the Year field.
Next to the matrix visual, click the forked-double arrow icon (which will expand all years down one level).
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.
To customize the Month field sort order, switch to Data view.
Add the MonthKey column to the Date table. This formula computes a numeric value for each year/month combination.
MonthKey = (YEAR('Date'[Date]) * 100) + MONTH('Date'[Date])
In Data view, verify that the new column contains numeric values (e.g. 201707 for July 2017, etc.).
In the Fields pane, ensure that the Month field is selected (when selected, it will have a dark gray background).
On the Column Tools contextual ribbon, from inside the Sort group, click Sort by Column, and then select MonthKey.
In the matrix visual, notice that the months are now chronologically sorted.
Task 4: 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.
Switch to Model view.
In the Date table, hide the MonthKey column.
In the Date table, create a hierarchy named Fiscal, with the following three levels:
Create the follow two model relationships:
- Date | Date to Sales | OrderDate
- Date | Date to Targets | TargetMonth
Hide the following two columns:
- Sales | OrderDate
- Targets | TargetMonth
Task 5: Mark the Date table
In this task, you will mark the Date table as a date table.
Switch to Report view.
In the Fields pane, select the Date table (not field).
On the Table Tools contextual ribbon, from inside the Calendars group, click Mark as Date Table, and then select Mark as Date Table.
In the Mark as Date Table window, in the Date Column dropdown list, select Date.
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 will work with time intelligence calculations in Lab 06B.
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 will create and format several measures.
Task 1: Create simple measures
In this task, you will create simple measures. Simple measures aggregate a single column or table.
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.
In the visual fields pane (located beneath the Visualizations pane), in the Values well, notice that Unit Price is listed.
Click 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 do not 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 will now take in this lab.
To create a measure, in the Fields pane, right-click the Sales table, and then select New Measure.
In the formula bar, add the following measure definition:
Avg Price = AVERAGE(Sales[Unit Price])
Add the Avg Price measure to the Values section in the matrix visual.
Notice that it produces the same result as the Unit Price column (but with different formatting).
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.
Use the snippets file definitions to create the following five measures for the Sales table:
- Median Price
- Min Price
- Max Price
- 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).
Switch to Model view, and then multi-select the four price measures: Avg Price, Max Price, Median Price, and Min Price.
For the multi-selection of measures, configure the following requirements:
- Set the format to two decimal places
- Assign to a display folder named Pricing
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.
Multi-select the Orders and Order Lines measures, and configure the following requirements:
- Set the format use the thousands separator
- Assign to a display folder named Counts
In Report view, in the Values well of the matrix visual, for the Unit Price field, click X to remove it.
Increase the size of the matrix visual to fill the page width and height.
Add the following five new measures to the matrix visual:
- Median Price
- Min Price
- Max Price
- Order Lines
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 expressions.
In Report view, select Page 1.
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 will implement a measure now to do just that.
In the table visual, remove the Target field.
Rename the Targets | Target column as Targets | TargetAmount.
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.
Create the following measure on the Targets table:
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.
Format the Target measure for zero decimal places.
You can use the Measure Tools contextual ribbon.
Hide the TargetAmount column.
Add the Target measure to the table visual.
Notice that the Target column total is now BLANK.
Use the snippets file definitions to create the following two measures for the Targets table:
- Variance Margin
Format the Variance measure for zero decimal places.
Format the Variance Margin measure as percentage with two decimal places.
Add the Variance and Variance Margin measures to the table visual.
Widen the table visual so all values are displayed.
While it appears all salespeople are not 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.
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.
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.
In this task, you will complete the lab.
Save the Power BI Desktop file.
Leave Power BI Desktop open.
In the next lab, you will enhance the data model with more advanced calculations using DAX.