Presentation is loading. Please wait.

Presentation is loading. Please wait.

Power BI for Excel DAX Functions

Similar presentations


Presentation on theme: "Power BI for Excel DAX Functions"— Presentation transcript:

1 Power BI for Excel DAX Functions
Your Instructor: Michelle Metzger

2 Terms of Use Use of this courseware is restricted to the student attending this TLG Learning class. No part of the courseware may be distributed in any form, electronic or printed, without written permission of a director of TLG Learning. If you suspect that this courseware has been unlawfully copied please phone or

3 Communication Expectations
Please communicate with me! Questions and comments are what will make this class great! My Expectation is that you will all walk away with a functional skill or two. NOT that you will memorize all of the techniques we use today. Your Expectations for you learning should be that you will be familiar enough with the concepts covered that you will be able to find the resources needed to complete the task.

4 Power BI for Excel Training Series
Level 1 Report Builders Level 2 Power BI Tools Level 3 Data Model Designers Level 4 DAX Functions

5 Course Outline Basic DAX Functionality Controlling Content & Values
Context Control Functions Contexts in Relationships Advanced DAX Concepts Time Intelligence Calculations Bonus Content: DAX Dashboard Techniques

6 Unit 1: Basic DAX Functionality

7 1. Basic DAX Functionality
Review of Calculated Columns PivotTable Functions Review of Measures Rules of Evaluation Evaluation Context Formatting DAX Code

8 Topic A: Calculated Column
Resides as a calculation in the Data Model Calculation is evaluated for every record regardless of the table filter Result is permanently stored in the Data Model May or may not use aggregate functions

9 Topic B: PivotTable Functions
PivotTable include a variety of built in functions that can be applied to implicit measures

10 Exercise 1-1: PivotTable Functions
Task 1: Create a PivotTable functions by adding the Sale Total column to the VALUES region multiple times. You will first create a % of Parent Row functions. Then add Calendar Year to the columns. Next create a Difference From… Function. This will produce a #NULL! error. Tell the students why they are getting it then move the CalendarYear field to the top of the ROWS region and the error will resolve itself because it does not see the empty context from the prior year in the same way. Finally create a % Difference From… function.

11 Topic B: Measure Implicit measures are created in the PivotTable
Explicit measures are created in the data model Formula/Function is stored in the data model not the result Result is recalculated each time it is added to a PivotTable/Pivot Chart Must always contain an aggregate function

12 Topic C: Rules of Evaluation
Understanding how to verbalize the meaning of values in a Pivot is vital! ProductKey = 373 Year = 2007 ProductKey = ALL Year = 2008 ProductKey = ALL Year = ALL

13 Rules of Evaluation When you write a DAX function, there are three rules that will always be followed. DAX Measures are always evaluated against the raw data (data model) not the PivotTable. Each value is calculated independently of the other values. DAX Measures are evaluated in these phases: Evaluated filters Apply filters Evaluate Arithmetic

14 Rules of Evaluation Measures are always evaluated against the raw data (data model) not the values in the visual. % of all source values = 99.93% % of all table values % of all source values

15 Rules of Evaluation Each value is calculated independently of the other values. 1 2 3 4 5 6

16 1 2 3 Rules of Evaluation DAX measures are evaluated in these phases:
Detect the context that will affect the evaluation Month=10 Year=2005 Product=320 2 3 Apply the context to the source data Evaluate the arithmetic to generate a result

17 Topic D: Evaluation Context
Every DAX function is limited to the context that is defined for it. The context is defined based on what type of function is created. Calculated Columns = Row Context Measures = Query & Filter Context

18 Evaluation Context Row Evaluation Context Calculated Columns
This context ignores all other contexts Is assessed upon creation of the column Cannot utilize values from other records or tables Calculated Column

19 Evaluation Context Query & Filter Evaluation Context
Implicit & Explicit Measures Are the result of fields placed in the rows, columns, & report regions of the PivotTable as well as slicers All functions are calculated after the context is evaluated The report builder can change this context at will Calculated Column Calculated Column Measures Calculated Column Calculated Column

20 Evaluation Context You must understand the evaluation context in order to ensure that results are correct The context can be changed by the PivotTable or by the measure syntax

21 Exercise 1-2: Evaluation Context
Task 1: Create a function to normalize the size values within the Product table. Investigate the results to see if everything worked the way we anticipated. Task 2: Create a PivotTable to display the results. Task 3: Repair the Switch Function. Task 4: Create a chart to display the result of the comparison.

22 Topic E: Formatting DAX Code
Format you DAX functions to be easy to read NO! YES! IF(HASONEVALUE(CustomValues[ShowValueAs] ), SUM(Sales[SaleTotal]) / VALUES(Custom Values[DivideBy]), SUM(Sales[SaleTotal])) IF(HASONEVALUE(CustomValues[ShowValueAs] ), SUM(Sales[SaleTotal]) / VALUES(Custom Values[DivideBy]), SUM(Sales[SaleTotal]))

23 Any Questions? Unit 1 Review Review of Calculated Columns
PivotTable Functions Review of Measures Rules of Evaluation Evaluation Context Formatting DAX Code Any Questions?

24 Unit 2: Controlling Content & Values

25 2. Controlling Content & Values
Controlling Values SWITCH Function Error Handling

26 Topic A: Controlling Values
Data Normalization/Cleansing Acronyms or abbreviated values Substitute with SWITCH Inconsistent values Replace using informational functions

27 Topic B: SWITCH Function
SWITCH is used to reduce the complexity of data This function allows you to substitute values based on a condition. You supply a value to be found then what to replace it with. Be sure that you include a final value to substitute. This server as the catch all value There will be times where the value in a cell just isn’t user friendly, or when there are different more commonly recognized ways to refere to categories in your data. This function allows you to take existing values and substitute other values in their place. Will be used in a Calculated Column never in a Calculated Field(Measure).

28 New Functions - SWITCH SWITCH Syntax
=SWITCH( table[column], condition, value {, n…} ) = SWITCH ( Product[Size], “S”, “Small” , “M”, “Medium” , “L”, “Large”, “Other” )

29 DAX SWITCH Function You can use a set of IF functions to accomplish this goal as well. However, using SWITCH is a cleaner way to work through many conditions. = IF( Product[Size] = “S”, “Small”, IF( Product[Size] = “M”, “Medium”, IF( Product[Size] = “L”, “Large”, “Other” ) ) ) There will be times where the value in a cell just isn’t user friendly, or when there are different more commonly recognized ways to refere to categories in your data. This function allows you to take existing values and substitute other values in their place. Will be used in a Calculated Column never in a Calculated Field(Measure).

30 Exercise 2-1: The SWITCH Function
Task 1: Create a function to normalize the size values within the Product table. Investigate the results to see if everything worked the way we anticipated. Task 2: Create a PivotTable to display the results. Task 3: Repair the Switch Function. Task 4: Create a chart to display the result of the comparison.

31 SWITCH Multiple condition
You may wish to test multiple conditions. The SWITCH function can do this. =SWITCH ( TRUE(), Products[Size-RAW]=”52” && Products[Category]=”Bikes”, “L Bike”, Products[Size-RAW]=”70” && Products[Category]=”Bikes”, “XL Bike”, “Other” )

32 Exercise 2-2: The SWITCH Function
Task 1: Create a function to normalize the Bike size values testing for the current size and that it is in the Bikes category. Investigate the results to see if everything worked the way we anticipated.

33 Topic C: Error Handling
Learning to intercept potential errors within the data model is key to creating a good data model This requires Understanding the types of errors you might encounter Understanding how to find the errors Understanding how to substitute values that will not cause errors

34 Types of Errors There are three main types of errors
Conversions Errors Arithmetic Errors Empty or Missing Values

35 Types of Errors Conversion Operations
DAX automatically converts between data types Sometimes this works, sometimes it does not. 89 + “14” = 103 89 & “14” = “8914” “apple.” + 8 = ERROR 89 + “1 + 4”

36 Types of Errors Arithmetic Operations
These errors are caused by trying to call a function or use an operator with invalid values. 10 / 0 = Infinity 0 / 0 = NaN 12 / “apple” = #ERROR

37 Types of Errors Empty cells, Blank values, Missing values
DAX handles all of these the same way. It returns a blank cell. 10 + __ = __ “apple” + __

38 Common DAX Functions Intercepting Errors
We never want those creating reports to receive an error in their reports. There are several ways we can handle them without client interaction.

39 Common DAX Functions There are many functions that help us to identify and substitute appropriate values ISBLANK ISERROR ISLOGICAL ISNONTEXT ISNUMBER ISTEXT All of these will return only TRUE or FALSE

40 Exercise 2-3: Handling Errors – Part 1
Explain that these columns are diagnostic column. That they are only used to help us identify what is wrong. As soon as we have identified the issue they should be removed. To fix this problem, the students will need to create a single column that can identify if there is an error and if so replace the value with a 0.

41 Exercise 2-3: Handling Errors – Part 2
Explain that these columns are diagnostic column. That they are only used to help us identify what is wrong. As soon as we have identified the issue they should be removed. To fix this problem, the students will need to create a single column that can identify if there is an error and if so replace the value with a 0.

42 Any Questions? Unit 2Review Controlling Values SWITCH Function
Error Handling Any Questions?

43 Unit 3: Context Control Functions

44 3. Context Control Functions
FILTER Function ALL Function Iterative Functions EARLIER Function CALCULATE Function Additional Uses of the ALL Function

45 Controlling Context Context is a tricky thing at times. There are many factors that will impact the results of the measures you write. Syntax of the measure Layout of the visual Slicers and filters Your job is to identify the possibilities of all three factors and to account for them in your measures.

46 Topic A: Iterative Functions
When developing data models a common concern is whether to create calculated columns or measures. Remember my recommendation is to create measures for all common calculations: Totals Averages Counts Properly accounting for aggregation within these measures is vital.

47 Topic A: Iterative Functions
You will be limited by the aggregate function you choose. Calculating the Total Sales for example: =SUM(Sales[UnitPrice] * Sales[Qty]) Often this function gets rewritten as follows: =SUM(Sales[UnitPrice])*SUM(Sales[Qty]) One problem, the SUM function does not allow arithmetic in the parameter! BAD: this is not mathematically sound

48 Iterative Functions Remember the Order of Mathematical Operations
How does aggregation fit it? It comes first. Operator Description Agg SUM, MAX, COUNTROWS ( ) Parentheses ^ Exponent * / Multiplication & Division + - Addition and Subtraction Operator Description ( ) Parentheses ^ Exponent * / Multiplication & Division + - Addition and Subtraction

49 Iterative Functions Here is how this function is being calculated: =SUM(Sales[UnitPrice])*SUM(Sales[Qty]) UnitPrice Qty $3.98 12 $14.97 8 $5.99 15 = [$24.94]*[35] = $872.90 $24.94 35

50 Iterative Functions DAX Iterative functions resolve this problem.
An Iterative function takes two parameters List or table of values Equation to be evaluated The equation is applied to each record in the table. These results are then aggregated.

51 Iterative Functions Iterative (X-Type) functions
Can apply an expression to each row of a table and then perform an aggregation on that expression. SUMX AVERAGEX COUNTX COUNTAX MINX MAXX = SUMX ( TableName, Formula ) = SUMX ( Sales, Sales[Quantity] * Sales[UnitPrice] ) )

52 Iterative Functions The Answer is to use an Iterative SUM function: =SUMX(Sales, Sales[UnitPrice]*Sales[Qty]) No calculated column required which leads to a smaller file size! UnitPrice Qty $3.98 12 $14.97 8 $5.99 15 $47.76 =[$47.76]+[$119.76]+[$89.85] $119.76 =$257.37 $89.85

53 Exercise 3-1: Iterative Functions
Task 1: Setup the PivotTable that will be used in the rest of the exercise. Task 2: Calculate the percentage.

54 Controlling Context Context is a tricky thing at times. There are many factors that will impact the results of the measures you write. Syntax of the measure Layout of the visual Slicers and filters Your job is to identify the possibilities of all three factors and to account for them in your measures.

55 Topic A: Iterative Functions
When developing data models a common concern is whether to create calculated columns or measures. Remember my recommendation is to create measures for all common calculations: Totals Averages Counts Properly accounting for aggregation within these measures is vital.

56 BAD: this is not mathematically sound
Iterative Functions You will be limited by the aggregate function you choose. Calculating the Total Sales for example: =SUM(Sales[UnitPrice] * Sales[Qty]) Often this function gets rewritten as follows: =SUM(Sales[UnitPrice])*SUM(Sales[Qty]) One problem, the SUM function does not allow arithmetic in the parameter! BAD: this is not mathematically sound

57 Iterative Functions Remember the Order of Mathematical Operations
How does aggregation fit it? It comes first. Operator Description Agg SUM, MAX, COUNTROWS ( ) Parentheses ^ Exponent * / Multiplication & Division + - Addition and Subtraction Operator Description ( ) Parentheses ^ Exponent * / Multiplication & Division + - Addition and Subtraction

58 Iterative Functions Here is how this function is being calculated: =SUM(Sales[UnitPrice])*SUM(Sales[Qty]) UnitPrice Qty $3.98 12 $14.97 8 $5.99 15 = [$24.94]*[35] = $872.90 $24.94 35

59 Iterative Functions DAX Iterative functions resolve this problem.
An Iterative function takes two parameters List or table of values Equation to be evaluated The equation is applied to each record in the table. These results are then aggregated.

60 Iterative Functions Iterative (X-Type) functions
Can apply an expression to each row of a table and then perform an aggregation on that expression. SUMX AVERAGEX COUNTX COUNTAX MINX MAXX = SUMX ( TableName, Formula ) = SUMX ( Sales, Sales[Quantity] * Sales[UnitPrice] ) )

61 Iterative Functions The Answer is to use an Iterative SUM function: =SUMX(Sales, Sales[UnitPrice]*Sales[Qty]) No calculated column required which leads to a smaller file size! UnitPrice Qty $3.98 12 $14.97 8 $5.99 15 $47.76 =[$47.76]+[$119.76]+[$89.85] $119.76 =$257.37 $89.85

62 Exercise 3-1: Iterative Functions
Task 1: Setup the Visual that will be used in the rest of the exercise. Task 2: Calculate the percentage.

63 Filtered Measures Creating filtered measures is a common way of providing complex analytical & statistical calculations to report builders. DAX contains several functions that allow you to set or change the filter context for a specific function. As you learn to master these functions you will be able to provide many meaningful calculations within the data models you build.

64 Topic A: FILTER Function
The FILTER function instructs the surrounding function to change the context for the table or column within the function. = FILTER( Table, Column=“ value ” ) = FILTER( Product, Product[ Color ] =“Red” ) Will always be used within an aggregate function. Dependent

65 FILTER Function Example
= COUNTROWS( FILTER( Product, Product[ Color ] =“Red” ) ) Evaluate the External Context. Assume that there is none. All records from the Product table are loaded into memory. Evaluate the Internal Context. The FILTER function defines the Filter Context for the COUNTROWS function. All records that do not have a color of red are removed from memory. Evaluate the aggregate.

66 Exercise 3-2: Filter Function
Task 1: Create an implicit measure to count the number of products. Task 2: Create basic functions using the FILTER function to show only red or black products.

67 ALL Function The ALL function instructs the surrounding function to ignore the query or filter context for the table or column within the function. = ALL ( Table | Table[column] ) = ALL ( Sales ) = ALL ( Sales[Product Category] ) Will always be used within an aggregate function. Dependent

68 ALL Function = COUNTROWS( ALL ( Sales ) )
Evaluate the External Context. Assume that there is a slicer on Sales[Product Category]. All records from the Sales table in the selected Category are loaded into memory. Evaluate the Internal Context. The ALL function defines the Filter Context for the COUNTROWS function. All unique records are added back into memory. Evaluate the aggregate.

69 ALL Function = COUNTROWS( ALL ( InternetSales[SaleTotal]) )
Evaluate the External Context. Assume that there is a slicer on InternetSales[Category]. All records from the InternetSales table in the selected Category are loaded into memory. Evaluate the Internal Context. The ALL function defines the Filter Context for the COUNTROWS function. Nothing in memory changes. The ALL reset a column that was unfiltered. Evaluate the aggregate.

70 ALL ( Products[SubcategoryKey])
ALL Function The ALL function does not always restore every single record to memory. The ALL function is really ALLDISTINCT. It restores a unique list of values for the specified column. ALL ( Products ) ALL ( Products[SubcategoryKey]) 606 38

71 ALL Function Here are a couple of examples:
AllTransactions =COUNTROWS( ALL(Sales) ) AllProductKeys =COUNTROWS( ALL(Sales) ) All Transactions: 60306 All Products: 60306

72 ALL Function Here are a couple of examples:
AllTransactions =COUNTROWS( ALL(Sales) ) AllProductKeys =COUNTROWS( ALL(Sales[ProductKey]) ) AllCustomerKeys =COUNTROWS( ALL(Sales) ) All Transactions: 60306 All Products: 60306 All Products: 158 All Customers: 60306

73 ALL Function Here are a couple of examples:
AllTransactions =COUNTROWS( ALL(Sales) ) AllProductKeys =COUNTROWS( ALL(Sales[ProductKey]) ) AllCustomerKeys =COUNTROWS( ALL(Sales[CustomerKey]) ) All Transactions: 60306 All Products: 158 All Customers: 18481 All Customers: 60306

74 ALL Function Here are a couple of examples:
AllTransactions =COUNTROWS( ALL(Sales) ) AllProductKeys =COUNTROWS( ALL(Sales[ProductKey]) ) AllCustomerKeys =COUNTROWS( ALL(Sales[CustomerKey]) ) All Transactions: 60306 All Products: 158 # Unique Sold Products: 158 # Sales Customers: 18481 All Customers: 18481 # Unique Sold Products # Unique Sales Customers

75 Exercise 3-3: ALL Function
Task 1: Create the Black and Red functions using the ALL function. Test the slicer and ensure that the numbers in these columns do not change. This is the result of the ALL function.

76 Earlier Function EARLIER function allows you to pull data from a column using a prior row context EARLIER is a dependent function It works in conjunction with the FILTER function

77 Earlier Function The syntax allows you to select how many contexts away from the current context you want to go. =EARLIER ( column, number )

78 Earlier Function The syntax allows you to select how many contexts away from the current context you want to go although it is rarely used =EARLIER ( column, number ) EXAMPLE: =EARLIER ( Product[ListPrice], 2 )

79 Advanced FILTER What if your report requires the number of all products that have a ListPrice less that $5? The Filter function can help you find this answer. This function loops through all of the rows and returns a table containing only matches. ProdID ListPrice 1 4.89 2 15.99 3 10.97 4 3.29 ProdID ListPrice 1 4.89 4 3.29 FILTER(Products, Products[ListPrice]<5)

80 Advanced FILTER The next step would be to aggregate this table into a single value. The COUNTROWS function is perfect for this. ProdID ListPrice 1 4.89 2 15.99 3 10.97 4 3.29 COUNTROWS( FILTER(Products, Products[ListPrice]<5) ) ProdID ListPrice 1 4.89 4 3.29 FILTER(Products, Products[ListPrice]<5) Result: 2

81 Advanced FILTER What if I need the number of products with a ListPrice greater than the current ListPrice? Evaluation context get’s really tricky when using iterative functions. You need a function that compares the external value (4.89) when looking at the internal values. ProdID ListPrice 1 4.89 2 15.99 3 10.97 4 3.29 ProdID ListPrice 1 4.89 2 15.99 3 10.97 4 3.29

82 Advanced FILTER Initial Context: ProdID = 1
COUNTROWS( FILTER(ALL(Products), Products[ListPrice] > Products[ListPrice]) ) New Context: ProdID = ALL 4.89 4.89 ProdID ListPrice 1 4.89 2 15.99 3 10.97 4 3.29 ProdID ListPrice 1 4.89 2 15.99 3 10.97 4 3.29 Nested

83 Advanced FILTER Result: 2 Initial Context: ProdID = 1
COUNTROWS( FILTER(ALL(Products), Products[ListPrice] > EARLIER( Products[ListPrice] ,1) ) ) COUNTROWS( FILTER(ALL(Products), Products[ListPrice] > Products[ListPrice]) ) New Context: ProdID = ALL Prev Context: ProdID = 1 ProdID ListPrice 1 4.89 2 15.99 3 10.97 4 3.29 ProdID ListPrice 1 4.89 2 15.99 3 10.97 4 3.29 Nested COUNTROWS( FILTER(ALL(Products), GreenTable[ListPrice] > EARLIER( BlueTable[ListPrice],1 ) ) ) 4.89 15.99 3.29 10.97 4.89 ProdID ListPrice #Greater 1 4.89 2 15.99 3 10.97 4 3.29 Result: 2

84 Exercise 3-4: Earlier Function
Task 1: Use the EARLIER function to create a calculated column that will calculate the Rank of each product against the others. Add the new function to a PivotTable to see the results. Task 2: Having a permanent column that holds onto the total sales per product may come in handy. This task will have the students create another calculated column. This one will use the same pattern as the last but will use a CALCULATE function instead of the COUNTROWS function.

85 CALCULATE Function This function allows us to alter the evaluation context very specifically. = CALCULATE ( Expression, Condition1, Condition2, … )

86 CALCULATE Function This function is our silver bullet. You can use it in almost any situation to control the context under which the function will be evaluated. = CALCULATE ( SUM ( Sales[ SalesAmount ] ), ALL ( Category ) )

87 CALCULATE Function The Calculate function allows changes to the context in two ways: Manual changes Products[ ModelName ] = “Mountain-200” Function based changes ALL( Products ) FILTER(Sales, Sales[Sale Total] > AVERAGE(Sales[Sale Total]) )

88 CALCULATE Function Now that understand how this function calculates, we can look at a simple example of the function. = CALCULATE ( SUM ( Sales[ SalesAmount ] ), ALL ( Category ) ) * Remember that a Calculated Field is strictly limited to its context.

89 CALCULATE Function What is our current evaluation context?
<Category=Bikes, Subcategory=Mountain Bikes, Color=Black >

90 CALCULATE Function Our current evaluation context is:
< Product Category=Bikes, Product Subcategory=Mountain Bikes, Color=Black > What is the context of the following function? = CALCULATE ( SUM ( Sales[ Sale Total ] ), ALL (Sales[Product Category] ), ALL (Sales[Product Subcategory] ) ) < Product Category=All, Product Subcategory=All, Color=Black >

91 CALCULATE Within the Rules of DAX
The CALCULATE function is still subject to the rules of all DAX functions: Detect the context for the current measure cell. Apply the context to the source data. Apply the external PivotTable context. Apply the new context specified in the function. Evaluate the arithmetic. Raw Source Data

92 How CALCULATE Works The CALCULATE function works in 3 steps:
Detect the context for the current Measure. The evaluation context is: Sum of Mountian-200 Sales for all Black Mountain Bikes These slicers set the filter context. There is no Query context. = CALCULATE ( SUM ( Sales[ Sale Total ] ), Products[ ModelName ] = “Mountain-200” ) This is the Measure This is only the name of the Measure!

93 How CALCULATE Works Apply the context to the source data.
The CALCULATE function works in 3 steps: Apply the context to the source data. Apply the external context. Updated Source Data

94 This is a change to the Filter context.
How CALCULATE Works The CALCULATE function works in 3 steps: Apply the context to the source data. Apply the context change within the CALCULATE function. The new filter context is: Sum of Mountian-200 Sales for all Mountain-200 Black Mountain Bikes = CALCULATE ( SUM ( Sales[ Sale Total ] ), Products[ ModelName ] = “Mountain-200” ) This is a change to the Filter context. 2 Updated Source Data

95 Evaluate the SUM of all remaining records.
How CALCULATE Works The CALCULATE function works in 3 steps: Evaluate the arithmetic. Updated Source Data = CALCULATE ( SUM ( Sales[ Sale Total ] ), Products[ ModelName ] = “Mountain-200” ) Evaluate the SUM of all remaining records.

96 CALCULATE Function What is our current evaluation context?
< Category=Bikes, ModelName=Mountain-100, Color=Black >

97 CALCULATE Function Our current evaluation context is:
< Category=Bikes, ModelName=Mountain-100, Color=Black > What is the context of the following function? = CALCULATE ( SUM ( Sales[ Sale Total ] ), Products[ ModelName ] = “Mountain-200” )

98 CALCULATE Function Why is the result blank? < Category=Bikes,
ModelName=Mountain-100 AND ModelName=Mountain-200, Color=Black >

99 CALCULATE Function = CALCULATE ( SUM ( Sales[ Sale Total ] ), ALL ( Products[ ModelName ] ), Products[ ModelName ] = “Mountain-200” ) < Category=Bikes, ModelName=All, Color=Black > < Category=Bikes, ModelName=Mountain-200, Color=Black >

100 How do we get the right function?
We need to calculate the %Margin for each color in each year. Our requirements: Allow the color to change the result of the function but it should always result in 100% Filtering the Product Category or Product Subcategory should not affect the percentage

101 Exercise 3-5: CALCULATE Function
Task 1: Create a % Product Sales column using the CALCULATE function and the ALL function. This column will serve as a percent to category column to complete the solution from the last exercise.

102 New Functions - ALLEXCEPT
Report users commonly want flexible complex percentage calculations. Resetting each column in a table is tedious. ALLEXCEPT allows you to reset all columns but the ones specified in the function parameters.

103 New Functions - ALLEXCEPT
ALLEXCEPT Syntax ALLEXCEPT( table, [column1], [column2] … ) ALLEXCEPT Example ALLEXCEPT( Sales, Sales[ProductKey], Sales[CustomerKey] )

104 New Functions - ALLSELECTED
ALLSELECTED is a great tool. It allows your function to filter to everything selected in a slicer. ALLSELECTED Syntax ALLSELECTED( table[column] ) CALCULATE( SUM([SalesTotal]), ALLSELECTED( Sales[MonthNum] ) ) No matter what months are chosen, This function will return the total for those months.

105 New Functions - ALLSELECTED
We will see an example of this later in class. ALLSELECTED in conjunction with the RANKX function will allow users to select certain items and find how they rank to each other rather than only to the whole.

106 New Functions - ALLSELECTED
ALLSELECTED Syntax ALLSELECTED( table[column] ) ALLSELECTED Example ALLSELECTED( Sales[ProductKey] )

107 New Functions - ALLNOBLANKROW
There are times when a parent table will cause a strange Blank row to show in a Pivot when the child is expanded. This happens when child rows exists without a value in the parent table. This function removes that blank row.

108 Exercise 3-6: Using All Functions
Task 1: Build the Net Sales, All Net Sales, and % of Total Sales functions. Task 2: Build a report to house the functions. Task 3: Create a function that will be sensitive to what the student selects in the slicer.

109 Any Questions? Unit 3 Review FILTER Function ALL Function
Iterative Functions EARLIER Function CALCULATE Function Additional Uses of the ALL Function Any Questions?

110 Unit 4: Contexts In Relationships

111 4. Contexts in Relationships
Working with Many Tables Row Context & Relationships Filter Context & Relationships VALUES Function

112 Working with Many Tables
The majority of data models will contain many tables You must understand how functions pull data across the relationships

113 Working with Many Tables
Every relationship has two connectors One – identified by a 1 Many – identified by a * A single table can have both connector types

114 Working with Many Tables
The connectors indicate the nature of data in the related tables. The “one” connector on the left means the ProductKey column in Product contains unique data used in the ProductKey column of the Sales table.

115 Working with Many Tables
The connectors indicate the nature of data in the related tables. The “many” connector on the right means ProductSubcategoryKey in Product contains many values that are unique in the ProductSubcategoryKey column of the ProductSubcategory table.

116 Working with Many Tables
Data can travel through these relationships unhindered. The Filter cannot. The filter can travel any number of relationships in the same direction. When the direction changes, the filter can no longer travel. The result? Unfiltered counts Customers: 18,484 Products: 158

117 Working with Many Tables
It is important to understand how to determine the direction. Both relationships are aligned with Many-to-One. Data can travel from Sales through Product to ProductSubcategory

118 Working with Many Tables
It is important to understand how to determine the direction. Left is One-to-Many; Right is Many-to-One Both relationships are aligned differently. Data can not travel from Customer to Product

119 Row Context & Relationships
Row Context Review It is created when you create a Calculated Column. The context includes every row in the table. The function is applied to each row one at a time. A row context is unaware of any context beyond the containing table. This context cannot traverse a relationship unaided.

120 Row Context & Relationships
There are two functions that allow us to overcome this limitation RELATED RELATEDTABLE Calculated Column

121 Row Context & Relationships
RELATED Function This function returns a related value from a related table. RELATED(<column>) RELATED(Product[ListPrice]) Sales Table Products Table Filter 537

122 Row Context & Relationships
RELATED gathers a single matching record from the parent/source table. Known as the one connector in a one-to-many relationship Remember which table is the unique list! RELATED RELATED

123 Row Context & Relationships
RELATEDTABLE Function This function returns a related value from a related table. RELATEDTABLE(<column>) RELATEDTABLE(Product) Products Table Sales Table Filter 535

124 Row Context & Relationships
RELATEDTABLE gathers multiple matching records from the child/reference table. Known as the many connector in a one-to-many relationship. Remember which table is the unique list! RELATEDTABLE RELATEDTABLE

125 Data Travel & Relationships
Within a Row c0ntext, data travels based on how the function is written. =COUNTROWS(RELATEDTABLE(Sales)) Context will flow from One-to-Many

126 Data Travel & Relationships
Within a Row Context Data Travels based on how the function is written. Context will flow from Many-to-One =RELATED(Customer[CustomerName])

127 Exercise 4-1: Row Context in Relationships
Task 1: Write a calculated column that will produce an error because you are in the wrong context. Task 2: Update the function using the RELATED function. Task 3: Write a function that will use the RELATEDTABLE function. The first function will fail. You will then repair it with the RELATEDTABLE function.

128 Filter Context & Relationships
Filter Contexts inherently interact with relationships Remember that a filter context is created when you create a Calculated Field Calculated Column Calculated Column Measures Calculated Column Calculated Column

129 Filter Context & Relationships
There are only two directions that context can shift One-to-many Many-to-one Context can only shift one direction in each PivotTable. No U-turns allowed! It is not the function but the PivotTable that determines the way the filter context can shift.

130 Filter Context & Relationships
The direction of context shift is defined by the Pivot Table not the function! Context will flow with the Pivot fields X

131 Filter Context & Relationships
The direction of context shift is defined by the Pivot Table not the function! X Context will flow With the Pivot fields

132 Filter Context & Relationships
This looks like the same direction to me! Unfortunately, this is not how the context sees it.

133 Filter Context & Relationships
The context sees this. Notice the difference? The context ALWAYS shifts in a straight line. From fields to measure. The context shift stops as soon as the direction changes.

134 Exercise 4-2: Filter Context in Relationships
Task 1: Create several functions that test the Filter context. First is the # of Sales function. Students will test the way this function works. They you will create the Product count and Customer count functions and add them to a Pivot. You will highlight that only one of the two functions will work correctly. Change the values on the ROWS region to prove this.

135 Context Shift So what do you do when you need values that are correctly filtered? You need a way of being able to filter both tables at once. You need to change the function used. Fortunately there are multiple ways to solve this problem. DISTINCTCOUNT VALUES

136 DISTINCTCOUNT This function references a specific column and calculates the number of unique values. =DISTINCTCOUNT( Table [ Column ] ) =DISTINCTCOUNT( Sales[ CustomerKey ] )

137 VALUES This function creates a list of distinct values within the current context for that field. =VALUES( Table [ Column ] ) =VALUES( Sales[ CustomerKey ] )

138 VALUES The greatest advantage of this function is not how it calculates but in what it returns. DISTINCTCOUNT is an aggregate function returns a single value VALUES is a scalar function is also an iterative function returns a single column of values

139 VALUES The result of this function can be used in numerous other functions. Its iterative nature is its strength. =COUNTROWS( VALUES( Sales[CustomerKey] ) ) =COUNTROWS( ) Result: 11

140 VALUES You will see many examples of how to use the VALUES function to complete complex aggregation later in this course. In the next activity, you will use it to resolve the issue with the filtering of the PivotTable.

141 Exercise 4-3: Functions in Relationships
Task 1: You will take the students through updating the functions with the VALUES function that will allow them both to work at the same time.

142 Row Context vs Filter Context
Do not interact with relationships Must use functions to force it to recognize the relationship The function used determines the direction the context shifts You change functions to control the direction the context shifts Filter Context Inherently interact with relationships No additional functions are needed The PivotTable created determines the direction the context shifts You change the PivotTable to change the direction the context travels

143 Any Questions? Unit 4 Review Working with Many Tables
Row Context & Relationships Filter Context & Relationships VALUES Function Any Questions?

144 Unit 5: Advanced Concepts

145 5. Advanced Concepts Circular Dependencies Controlling Totals
Advance Hierarchy Concepts

146 Changing Context You can force a calculated column into a filter context It will still carry the context with it Calculated Column Calculated Column Calculated Column Calculated Column

147 Changing Context Use the CALCULATE function within a calculated column
=CALCULATE( SUM(Sales[ SaleTotal ]) ) Products Table Sales Table Filter 214

148 Changing Context In Unit 3 you created the following function:
=CALCULATE(SUM(Sales[Sale Total]), Products[ProductKey]=EARLIER(Products[ProductKey])) This function produced the correct answer Why? Because is changed its context from a row to a filter

149 Exercise 5-1: Circular Dependencies
Task 1:

150 Circular Dependencies
Is a condition where a single function has to loop back on itself to produce a result. TotalProductSales =CALCULATE(SUM(Sales[Sale Total]), Products[ProductKey]= EARLIER(Products[ProductKey])) Sales Rank =COUNTROWS( FILTER(ALL(Products), Products[TotalProductSales] > EARLIER( Products[TotalProductSales]) ) )+1

151 Circular Dependencies
The issue here is more of a misunderstanding of how CALCULATE changes the context The CALCULATE function is already filtering the Sale Total based on the Product Key The filter is completely unnecessary TotalProductSales =CALCULATE(SUM(Sales[Sale Total])) =CALCULATE(SUM(Sales[Sale Total]), Products[ProductKey]= EARLIER(Products[ProductKey]))

152 Circular Dependencies
This issue can arise in column calculations as well Just be sure to carefully test each function to avoid this error Sale Total =Sales[Unit Price] * Sales[Quantity] – [Discount] Discount =IF([Sale Total]-[Cost Total]>3,([Sale Total]-[Cost Total])*.2,0)

153 Exercise 5-2: Circular Dependencies
Task 1:

154 Topic B: Controlling Totals
Common Question: Can I control when sub and grand totals appear? YES!! There are several functions we can use to test when multiple values or filters are present This indicates that a total is being calculated We can decide what to do with it when we find it

155 Topic B: Controlling Totals
Common Question: Can I control when sub and grand totals appear? YES!! There are several functions we can use to test when multiple values or filters are present This indicates that a total is being calculated We can decide what to do with it when we find it

156 HASONEVALUE This function will return true if the column listed has only 1 value in the result set =HASONEVALUE ( columnName ) EXAMPLE: =HASONEVALUE (Dates[Month] ) =IF(HASONEVALUE (Dates[Month] ), TRUE(), FALSE() )

157 HASONEVALUE We use this function to make our pivots easier to read

158 Advanced Date Functions
Here’s how it works: It follows the rules of all DAX functions Every value is calculated from the raw data, including the subtotals and grand totals. When a subtotal is being calculated there will be several rows returned. This result comes from limiting the Years to containing only 1 value.

159 HASONEVALUE We use this function to make our pivots easier to read
=IF(HASONEVALUE (Dates[Month] ), TOTALYTD(SUM(Sales[Sale Total]),Dates[FullDate]), BLANK() ) Perfect Right?

160 HASONEVALUE Not Quite, Notice what happens when we show the 3rd quarter If we are trying to avoid subtotals we just failed

161 ISFILTERED There is a function that is closer to what we really want
=ISFILTERED ( columnName ) EXAMPLE: =ISFILTERED (Dates[Month] ) =IF(ISFILTERED(Dates[Month] ), TRUE(), FALSE() )

162 ISFILTERED We use this function to make our pivots easier to read
=IF( ISFILTERED (Dates[Month] ), TOTALYTD(SUM(Sales[Sale Total]),Dates[FullDate]), BLANK() )

163 ISFILTERED Notice that applying the function has resolved this issue!

164 ISFILTERED Not so fast! What happens when I slice it?
EEK! There’re back

165 HASONEFILTER Now we reach the ultimate solution
=HASONEFILTER ( columnName ) EXAMPLE: =HASONEFILTER (Dates[Month] ) =IF(HASONEFILTER(Dates[Month] ), TRUE(), FALSE() )

166 HASONEFILTER We use this function to make our pivots easier to read
=IF( HASONEFILTER(Dates[Month] ), TOTALYTD(SUM(Sales[Sale Total]),Dates[FullDate]), BLANK() )

167 HASONEFILTER When the user select a single month there is only 1 filter and the subtotal appear

168 HASONEFILTER When the user selects two or more months the function correctly removes the subtotals

169 Exercise 5-3: Controlling Totals
Task 1:

170 Topic C: Advanced Hierarchy Concepts
Tables may contain many columns that are related to each other. Many times this is a natural part of the data. Sometimes this is generated by business practice as well. Most Specific Granular Least Specific Granular Day Month Quarter Year Most Specific Granular Least Specific Granular Category SubCategory Product

171 Building on Multiple Tables
You may have a hierarchy that extends more than 1 table. You cannot create a hierarchy on more than one table. So what can we do?

172 Building on Multiple Tables
The RELATED function can pull data into the table containing the hierarchy. =RELATED( Category[CategoryName] ) =RELATED( SubCategory[SubCategoryName] )

173 Exercise 5-4: Multi-Table Hierarchies

174 Any Questions? Unit 5 Review Circular References Controlling Totals
Advance Hierarchy Concepts Any Questions?

175 Unit 6: Time Intelligence Calculations

176 6. Time Intelligence Calculations
Working with Date Tables Calculating Operating Periods Daily Calculations DAX Date Functions Prior Year Functions Simple Moving Averages

177 Topic A: Working with Date Tables
You must have one date table This source table must meet the following requirements: Granularity must be to the day Must contain consecutive dates Must contain a Date Type column Must be marked as a date table If these requirements are not met, DAX Time Intelligence functions will not work right

178 Working with Date Tables
Dealing with Multiple Dates Create multiple Date tables Advantages Flexibility for the Report Builders Easier to maintain

179 Working with Date Tables
Dealing with Multiple Dates Create functions that activate relationships Advantages High level of control Measures are easy to use Disadvantages Difficult to maintain too many measures Very inflexible

180 USERELATIONSHIP Specifies the relationship to be used within a function =USERELATIONSHIP( <columnName>, <columnName> ) EXAMPLE: =CALCULATE( SUM(Sales[Sale Total]), USERELATIONSHIP( Sales[ShipDateKey], Dates[DateKey] ) )

181 Exercise 6-1: USERELATIOSHIP
Task 1: Have the students create the DateComparison worksheet. Then have them create the Shipping Sales and Due Date Sales measures. They will add both to a Pivot table to see how the values vary. You can go into the data model to show how the dates difference if you feel the students need to see it.

182 Topic B: Operating Periods
Not all businesses operate 7 days a week 365 days a year For these businesses, more work needs to be done to get correct date metrics It all starts by calculating the operating days within the reporting period

183 Operating Periods The WEEKDAY function will identify what day of the week a particular date is =WEEKDAY ( Date , Return-Type )

184 Operating Periods The WEEKDAY function will identify what day of the week a particular date is =WEEKDAY ( Date , Return-Type ) EXAMPLE: =WEEKDAY ( OrderDates[Date], 2 )

185 Operating Periods Now that we know what day of the week an order was placed on we can begin to compare Comparing sales on Monday to sales on Saturday may be meaningless Comparing daily averages that include days that there was no opportunity for the event to occur is also meaningless

186 Operating Periods We can create Measures that filter to specific days of the week Friday Sales:=CALCULATE( SUM(Sales[SaleTotal]), OrderDates[Weekday]=”5” )

187 Operating Periods Calculating regular operating days can be done with a simple function For a Weekday period Weekdays can be set to 1, Weekends to 0. For a Weekend period Weekends can be set to 1, Weekdays to 0. =IF( OrderDates[Day of Week] > 5, 0, 1 ) WARNING! If working days are not regular this column will need to be manually created!

188 Operating Periods Now that we can identify what operating period a date is within, we can calculate a Daily Sales Average for each operating period Weekday Sales Average:=SUM ( Sales[Sale Total] ) / SUM ( OrderDates[Weekday] ) Weekend Sales Average:=SUM ( Sales[Sale Total] ) / SUM ( OrderDates[Weekend] )

189 Exercise 6-2: Operating Periods
Task 1: Have the students create calculations that will calculate the day of the week as well as whether that day is a weekday or weekend. Task 2: Have the students create measures that will calculate the weekday sales average. The first function will not return the return the correct value because it is not sensitive to whether a day is a weekday or weekend. Have the students write the correct calculations.

190 Topic C: Daily Calculations
Remember that PivotTables will automatically remove dates where no sales occur This allows these calculations to work correctly when sales occur consecutively The problem is when entire weeks or months go by with any sales

191 It is the denominator that needs to be sensitive.
Daily Calculations We will have to write a function that will check if there are sales within that period before we SUM the Working Days attribute Daily Sales Average:=SUM ( Sales[Sale Total] ) / COUNT ( OrderDates[OrderDate] ) The VALUES function you learned earlier will help with this The numerator is fine. It is the denominator that needs to be sensitive.

192 > 0 > 0 Daily Calculations Corrected Function
=SUM ( Sales[SaleTotal] ) / SUMX ( VALUES ( OrderDates[MonthName] ), CALCULATE ( IF ( COUNTROWS (Sales) > 0, COUNT(OrderDates[OrderDate] ) ) 3) The CALCULATE function filters the sales to that value. 1) The VALUES function is changed into a list. 4) If the value is greater than 0, the SUM function will run & the value is sent to a temp table. 5) This process continues through all items in the VALUES function. 2) The first value is pushed down to the IF function. TempTable 19 22 24 18 TempTable 19 22 24 18 TempTable 19 22 24 TempTable 19 TempTable 19 TempTable 19 22 > 0 > 0

193 6) The next step is that the values within the Temp table are summed.
Daily Calculations Corrected Function =SUM ( Sales[SaleTotal] ) / SUMX ( VALUES ( OrderDates[MonthName] ), CALCULATE ( IF ( COUNTROWS (Sales) > 0, SUM(OrderDates[OrderDate] ) ) 6) The next step is that the values within the Temp table are summed. 248 = $698, / 248 = $2,816.34

194 Exercise 6-3: Working with Missing Periods
Task 1: Have the students create a basic Missing Daily Average function. Have the students create the corrected average function that takes into consideration what days did and did not have sales on them.

195 Topic D: To-Date Functions
It is very common that you will need to calculate how much has been spent from Jan 1 to today or to- date We call these types of aggregates To-Date Functions DAX has three unique To-Date functions: TOTALYTD TOTALQTD TOTALMTD

196 To-Date Functions These functions allow for a minimal amount of flexibility in calculations. There is a single filter that can be applied to the execution of the function. You will learn to create more flexible variations of this function later today.

197 To-Date Functions Year-To-Date
=TOTALYTD ( Expression, Dates [,Filter] [,YearEndDate] )

198 To-Date Functions Year-To-Date
=TOTALYTD ( Expression, Dates [,Filter] [,YearEndDate] ) =TOTALYTD ( SUM( Sales[Sale Total]) , Dates[FullDate] ) =TOTALYTD ( SUM(Sales[Sale Total]) , Dates[FullDate] , Products[Category] = “Bike” ) ALWAYS use the Date table!!!

199 To-Date Functions Fiscal Year-To-Date
=TOTALYTD ( Expression, Dates, [Filter], [YearEndDate] ) =TOTALYTD ( SUM ( Sales[SaleTotal] ), Dates[FullDate], “6-30”)

200 To-Date Functions Quarter-To-Date
=TOTALQTD ( Expression, Dates, [Filter] )

201 To-Date Functions Month-To-Date
=TOTALMTD ( Expression, Dates, [Filter] )

202 Exercise 6-4: To-Date Functions
Task 1: Create the TOTALYTD function. Add it to a PivotTable and investigate how it works. Task 2: Create the Fiscal Year-to-date functions Task 3: Create the Quarter-to-date function Task 4: Create the Month-to-date function.

203 Date Period Functions It is very common that you will need to see what the balance was for the beginning or end of a month, quarter, or year We call these types of aggregates Date Period Functions DAX has six unique Date Period functions: OPENINGBALANCEYEAR CLOSINGBALANCEYEAR OPENINGBALANCEQUARTER CLOSINGBALANCEQUARTER OPENINGBALANCEMONTH CLOSINGBALANCEMONTH

204 Date Period Functions CLOSINGBALANCE & OPENINGBALANCE
=CLOSINGBALANCEYEAR ( Expression, Dates [, Filter] [,YearEndDate] )

205 Date Period Functions CLOSINGBALANCE & & OPENINGBALANCE
=CLOSINGBALANCEYEAR ( Expression, Dates [, Filter] [,YearEndDate] ) =CLOSINGBALANCEYEAR( SUM (Balances[Balance] ), BalanceDate[Date] ) ALWAYS use the Date table!!!

206 Date Period Functions Fiscal CLOSINGBALANCE & OPENINGBALANCE
=OPENINGBALANCEYEAR( Expression, Dates [, Filter] [, YearEndDate] ) =OPENINGBALANCEYEAR( SUM ( Sales[SaleTotal] ), Dates[FullDate], “6-30”)

207 Date Period Functions CLOSINGBALANCE & OPENINGBALANCE
=CLOSINGBALANCEQUARTER ( Expression, Dates [, Filter] ) =CLOSINGBALANCEMONTH ( Expression, Dates [, Filter] )

208 Date Period Functions Balance tables may not record balances every day
PivotTable would be filled rows containing only a balance value =IF( COUNTROWS(Balances)>0, CLOSINGBALANCEMONTH( SUM(Balances[Balance]),BalanceDate[Date]), BLANK() ) If True If False

209 Exercise 6-5: Closing Balance Functions
Task 1: Have the students create a measure that will calculate the closing balance for the month. The first function will calculate a value for every day even though there was not a balance recorded for each day. Have the students update the function with an if statement to place blank values in when there is no balance recorded. Task 2: Have the students create a version of the function for the Quarter and the Year as well.

210 Topic E: Advanced Date Functions
The TOTALYTD function you just learned is not very flexible. When you need a more flexible option, you can manually write a YTD, QTD, or MTD function. Manually writing the TOTALYTD function requires a new function.

211 Advanced Date Functions
This function returns a single column list of dates within the current year. =DATESYTD (Dates [,YearEndDate] ) =DATESQTD (Dates) =DATESMTD (Dates)

212 Advanced Date Functions
Combining the DATESYTD function with the CALCULATE function will allow you to create a manual version of the year-to-date function. =CALCULATE ( [Total Sales] , DATESYTD(Dates[FullDate]) )

213 Advanced Date Functions
You can now add filters that will allow you to control the evaluation context as many ways as needed. =CALCULATE ( [Total Sales] , ALL(Dates), ALL(Products), DATESYTD(Dates[FullDate]) )

214 Exercise 6-6: YTD Using CALCULATE
Task 1: Have the students create a YTD using the CALCULATE function

215 Advanced Date Functions
Getting a Year-to-date or Month-to-date can be quite helpful, but what if I want a “never ending-to- date” function? We call this a Running Total.

216 Advanced Date Functions
Calculating a Running Total will combine the CALCULATE function with the FILTER function It also requires the use of a conditional expression && = both conditions must return true. || = one condition must return true.

217 Advanced Date Functions
For Example: =FILTER(Dates[FullDate] <= MAX( Dates[FullDate] ) ) =FILTER(Dates[FullDate] <= MAX(Dates[FullDate]) && OrderDates[OrderYear] = VALUES( OrderDates[OrderYear]) )

218 Advanced Date Functions
YTD functions can be written using this syntax =CALCULATE ( [Total Sales] , FILTER( ALL ( Dates ), Dates[FullDate] <= MAX(Dates[FullDate]) && Dates[FullDate] = VALUES(Dates[OrderYear]) )

219 Advanced Date Functions
Running Totals are written using a modified version of this syntax. Simply leave off the year condition. =CALCULATE ( [Total Sales] , FILTER( ALL ( Dates ), Dates[FullDate] <= MAX(Dates[FullDate] ) ) )

220 Advanced Date Functions
When creating running totals, subtotals and grand totals can be problematic. They will make sense if all years are present. If filtered on year, they will lose their meaning. Be sure to create functions that are sensitive to a non-consecutive date selection.

221 Advanced Date Functions
Here is the Running Total measure rewritten using HASONEVALUE =IF ( HASONEVALUE ( Date[Year] ) , CALCULATE ( [Total Sales] , FILTER( ALL ( Dates ), Dates[FullDate] <= MAX( Dates[FullDate] ) ) ) , BLANK( ) Expression Value if True Value if False

222 Advanced Date Functions
Here is the Running Total measure rewritten using HASONEVALUE =IF ( HASONEVALUE ( Date[Year] ) , CALCULATE ( SUM(Sales[Sale Total]) , FILTER( ALL ( Dates ), Dates[FullDate] <= MAX( Dates[FullDate] ) ) ) , BLANK( )

223 Exercise 6-7: Running Totals
Task 1: Have the students create the running total function. Have the pay attention to the subtotals that exist within it and review the HASONEVALUE function. Have them correct the function using HASONEVALUE.

224 Topic F: Prior Year Functions
Knowing what happened last year is important. There are several ways to pull data from a prior year into an adjacent field using DAX. Microsoft has simplified this task with a custom function: SAMEPERIODLASTYEAR.

225 Prior Year Functions This function will return all dates from the same period in the prior year =SAMEPERIODLASTYEAR ( dates ) EXAMPLE: = SAMEPERIODLASTYEAR ( Dates[FullDate] )

226 Prior Year Functions What if you need the ability to go more than 1 year back? What if you need to go forward for budget analysis? DAX has two useful functions for moving through time: DATEADD PARALLELPERIOD

227 PARALLELPERIOD cannot calculate days.
Prior Year Functions This function will display dates shifted either forward or backward in time by the specified number of intervals from the dates in the current context =DATEADD ( dates, number_of_Intervals, interval ) PARALLELPERIOD cannot calculate days.

228 Prior Year Functions This function will display dates shifted either forward or backward in time by the specified number of intervals from the dates in the current context =DATEADD ( dates, number_of_Intervals, interval ) EXAMPLE: = DATEADD ( Dates[FullDate], -1, YEAR )

229 Prior Year Functions This function will return dates that represent a period parallel to the dates in the specified dates column, in the current context, with the dates shifted a number of intervals either forward in time or back in time =PARALLELPERIOD ( dates, number_of_Intervals, interval )

230 Prior Year Functions This function will return dates that represent a period parallel to the dates in the specified dates column, in the current context, with the dates shifted a number of intervals either forward in time or back in time =PARALLELPERIOD ( dates, number_of_Intervals, interval ) EXAMPLE: = PARALLELPERIOD (Dates[FullDate], -1, YEAR )

231 Prior Year Functions DATEADD PARALLELPERIOD
Gathers only similar dates from the two periods Gathers all dates from the specified period Previous Month 1 3 4 8 10 11 12 15 Current Month 1 8 15 24 Previous Month 1 8 15 24 Current Month 1 8 15 24

232 Prior Year Functions Prior Year Sales (SAMEPERIODLASTYEAR)
=CALCULATE ( SUM( Sales[Sale Total] ), SAMEPERIODLASTYEAR( Dates[FullDate] ) ) Prior Year Sales (PARALLELPERIOD) PARALLELPERIOD( Dates[FullDate], -1, YEAR )

233 Prior Year Functions You will see that the PY Sales column for contains the same values as the Net Sales for 2012

234 Prior Year Functions You can also calculate YTD using this method
SUM( Sales[SaleTotal] ), SAMEPERIODLASTYEAR( DATESYTD( Dates[FullDate] ) ) )

235 Prior Year Functions Quantifying the change between two years can be a key component to many financial reports. This calculation is commonly called a Year-Over-Year or YOY calculation.

236 Prior Year Functions Start with a Prior Year measure: YOY Sales:
=CALCULATE ( SUM(Sales[Sale Total] ), DATEADD( Dates[FullDate], -1, YEAR ) ) YOY Sales: SUM(Sales[Sale Total] ) - [ Py Sales ]

237 Prior Year Functions Most of the time you will want the YOY to be displayed as a percentage. Keep in mind that there may be times when there is no previous year sales, this would cause an error that we need to prepare for.

238 Prior Year Functions % YOY Sales: Using IF Using DIVIDE
=IF ( [ PySales ] = 0, BLANK( ), [ YoySales ] / [ PySales ] ) Using DIVIDE =DIVIDE( [ YoySales ] , [ PySales ] )

239 Exercise 6-8: Prior Year Functions
Task 1: Have the students create the PY Sales function and investigate how it works. Have them use the DATEADD function to create a PY over 2 years. Task 2: Have the students create a PY YTD function Task 3: Have the students create a YOY Sales and %YOY sales function.

240 Topic F: Moving Averages
One of the best ways to gain insight into the trends of a business A moving average is calculated against a number of previous months

241 Moving Averages Creating a Moving Average will take several steps
Identifying the beginning and end of the period Calculating the Average Setting the Correct Context for the Average Ensuring that it is calculating for only a single period at a time

242 FIRSTDATE/LASTDATE This function will calculate the first or last date within a period FIRSTDATE( <dates> ) OR LASTDATE( <dates> ) FIRSTDATE( Sales[OrderDate] ) OR LASTDATE( Sales[OrderDate] )

243 Moving Averages Step 1: Calculating the start and end dates
FIRSTDATE( PARALLELPERIOD(OrderDates[OrderDate], -2, month ) ) LASTDATE( PARALLELPERIOD(OrderDates[OrderDate], 0, month ) )

244 DATESBETWEEN Returns a table that contains a column of dates within a specified range DATESBETWEEN( <dates> , <start_date>, <end_date> ) DATESBETWEEN( OrderDates[OrderDate], OrderDates[OrderDate], OrderDates[OrderDate]+30)

245 Moving Averages Step 1: Using these to create a period
DATESBETWEEN( OrderDates[OrderDate] , FIRSTDATE( PARALLELPERIOD(OrderDates[OrderDate], -2, month ) ) , LASTDATE( PARALLELPERIOD(OrderDates[OrderDate], 0, month ) ) )

246 2. Calculate the Average Calculating the average is pretty basic
Be sure that the correct period is used SUM(Sales[SaleTotal]) / COUNTROWS( VALUES(OrderDates[MonthNumber]) )

247 Moving Averages Step 2: Using these to create a period
CALCULATE( SUM(Sales[SaleTotal]) / COUNTROWS( VALUES(OrderDates[MonthNumber])), DATESBETWEEN( OrderDates[OrderDate] , FIRSTDATE( PARALLELPERIOD(OrderDates[OrderDate], -2, month ) ) , LASTDATE( PARALLELPERIOD(OrderDates[OrderDate], 0, month ) ) )

248 3. Setting the Correct Context
You will need to make sure that when the DATESBETWEEN function is calculated it sees all dates without a filter All you need is an ALL filter on the OrderDates ALL( OrderDates )

249 Moving Averages Step 3: Ensuring all dates are evaluated
CALCULATE( SUM(Sales[SaleTotal]) / COUNTROWS( VALUES(OrderDates[MonthNumber])), DATESBETWEEN( OrderDates[OrderDate] , FIRSTDATE( PARALLELPERIOD(OrderDates[OrderDate], -2, month ) ) , LASTDATE( PARALLELPERIOD(OrderDates[OrderDate], 0, month ) ) ) , ALL(OrderDates) )

250 4. Calculating One Period at a Time
The final step to calculating correctly is to ensure that only one period is evaluated at a time This can be accomplished by using an IF function IF( COUNTROWS( VALUES( OrderDates[MonthNumber] ) ) = 1 , <true>, <false> )

251 Moving Averages Step 4: Limiting evaluation to a single month
IF( COUNTROWS(VALUES(OrderDates[MonthNumber])) = 1, CALCULATE( SUM(Sales[SaleTotal]) / COUNTROWS( VALUES(OrderDates[MonthNumber])), DATESBETWEEN( OrderDates[OrderDate] , FIRSTDATE( PARALLELPERIOD(OrderDates[OrderDate], -2, month ) ) , LASTDATE( PARALLELPERIOD(OrderDates[OrderDate], 0, month ) ) ) , ALL(OrderDates) ) If True No False Condition

252 Exercise 6-9: Moving Averages
Task 1: Have the students create the Moving 3 month average function. Then the moving 6 month and moving 9 month functions.

253 Any Questions? Lesson 6 Review Calculating Operating Periods
Daily Calculations DAX Date Functions Advanced Date Functions Prior Year Functions Simple Moving Averages Any Questions?

254 Bonus Content: DAX Dashboard Techniques

255 DAX Dashboard Techniques
Parameter Tables Banding Ranking Initializing Slicers Symbol Slicers Slicers for Sort Order Current Date Slicers

256 Parameter Tables Parameter tables allow you to store variables that can be used to control the values displayed in a report Parameter tables are unrelated to the data model They are used internally by DAX functions to modify their behavior

257 Parameter Tables Take this PivotTable as an example:
It is difficult to tell whether the values are in millions or billions

258 Parameter Tables We can create a parameter table allowing the user to change the scale using a slicer

259 Parameter Tables This is accomplished in 2 steps:
Create the parameter table Write a measure to activate it IF( HASONEVALUE(ShownValues[ShowValueAs] ), SUM(Sales[SaleTotal]) / VALUES(ShownValues[DivideBy]), SUM(Sales[SaleTotal]) ) True False

260 Exercise 7-1: Parameter Tables
Task 1: Have the students create a parameter table within Excel that will serve as the values a user can divide the real values by. Task 2: Have the students create the measure that will activate the division and make the slicer work. Add the new measure to the PivotTable. Also add a slicer on the new parameter table and test it out.

261 Banding Banding is a technique that allows you to create divisions within your data that do not exist explicitly Banding can be done on any column but usually on numeric columns

262 Banding A weather map is broken into bands by temperature.

263 Banding First you must create an unrelated table that defines the bands

264 Banding Possible Calculated Column Syntax: = CALCULATE(
VALUES ( PriceBands[BandName] ), Filter ( PriceBands, PriceBands[Min] <= Product[ListPrice] && PriceBands[Max] > Product[ListPrice] )

265 Exercise 7-2: Banding Task 1: Have the students create the table that will serve as the rules for the banding. Task 2: Have the students switch to the Product table and create the calculated column that will hold the new information. Task 3: Have the students create a PivotTable to display the results. They will see blank values. Discuss that these ranges may not be able to simply change. Have them create an IF function to change the Blank results to “Out of Range”) Task 4: Have the students create a column that can be used to sort the ranges in the desired order based on the ID column of the PriceRanges table.

266 Ranking Ranking is the process of comparing similar items to one another based on a common trait and assigning position to those traits Top 10 Products by Sales Volume

267 Important Functions RANKX
This function will allow you to calculate the rank of values within a table =RANKX ( table, [expression], [value], [order], [ties] ]… ) EXAMPLE: =RANKX ( ALL( Products ), SUMX( RELATEDTABLE( FactInternetSales ), [SalesAmount] ) )

268 Important Functions This function has three optional parameters that make this function very powerful. =RANKX ( table, [ expression, [value], [order], [ties] ]… ) value (Optional) Any DAX expression that returns a single scalar value whose rank is to be found. When the value parameter is omitted, the value of expression at the current row is used instead.

269 Important Functions This function has three optional parameters that make this function very powerful. =RANKX ( table, [ expression, [value], [order], [ties] ]… ) order

270 Important Functions This function has three optional parameters that make this function very powerful =RANKX ( table, [ expression, [value], [order], [ties] ]… ) ties

271 RANKX Steps the RANKX functions takes:
The Product list is iterated for each product This table is then presented to the expression parameter. In our case all 4 rows are summed resulting in 550 Finally RANKX assigns a ranking. There is only 1 result so the result is 1 Shoe 240 Bike 130 Shirt 110 Helmet 70

272 RANKX Shoe is passed into RANKX as the Product
=RANKX ( Product , Sales[SaleTotal] ) Shoe is passed into RANKX as the Product =RANKX ( Shoe, Sales[SaleTotal]) =RANKX ( Bike, Sales[SaleTotal]) =RANKX ( Shirt, Sales[SaleTotal]) =RANKX ( Helmet, Sales[SaleTotal]) The context has now changed. Only the Sales for a single product are being considered! This is why it is ranked 1 Shoe 240 Bike 130 Shirt 110 Helmet 70

273 RANKX =RANKX ( ALL(Products) , [SumOfSales] ) This will fix the issue of ranking but only so long as no slicer is used Even when the context is changed, the ranking stays the same because it will always look at all products

274 Important Functions ALLSELECTED
This function allows you to limit the context to only the selected records from the data. =ALLSELECTED( table | column )

275 RANKX =RANKX ( ALLSELECTED(Products) , [SumOfSales] ) This will fix the issue of ranking as well as allowing the table to re-Rank when sliced.

276 Exercise 7-3: Ranking Task 1: Have the students create the RANKX function. They should see that every value is given first place. This is because the context is limited to a single item at a time. Task 2: Have the students create a second function that will correctly evaluate the RANKX against all products. Task 3: Have the students create a final function that will perform a selective ranking using the ALLSELECTED function.

277 Topic D: Advanced Slicer Techniques
Creating user friendly reports is often more about the correct choice of slicers than it is about the layout of the report Initializing Slicers Symbol Slicers Sort Order Slicers Date Based Slicers

278 Initializing Slicers Have you ever had to add a huge list of items to a slicer? There’s got to be a better way to handle so many options!!

279 Initializing Slicers Slicers not only filter data, they also filter each other Create a column that contains the initials and use them as a filter for your large list

280 Exercise 7-4: Initializing Slicers
Task 1: Have the students create two calculated column. One that will extract the first letter of the first name and one that will extract the first letter of the last name. Task 2: Add the new columns as slicers on the PivotTable. Rearrange them so that they a placed nicely above the current slicer. Task 3:

281 Using Symbols in Slicers
Humans think in pictures, using them in slicers is a great tool to make reports user friendly

282 Using Symbols in Slicers
There are many fonts that contain images. All of the fonts listed below are installed with the OS and Microsoft Office: Symbol Webdings Wingdings Wingdings 2 Wingdings 3

283 Using Symbols as Slicers
Builder columns are needed to use as a base for the slicer IF() functions are generally used to generate the correct symbol for each record

284 Using Symbols as Slicers
Builder columns are needed to use as a base for the slicer IF() functions are generally used to generate the correct symbol for each record Format the Slicer settings

285 Exercise 7-5: Symbol Slicers
Task 1: Have the students create a calculated column that will return “C” if the purchase volume is above average and “D” if it is below average. Task 2: Have the students add the new slicer to the PivotTable on the Customer Analysis worksheet. Next take them through re-formatting the slicer to use the Wingdings font for the choices.

286 Using Slicers for Sort Order
User Friendliness is paramount in reports Creating slicers to control sort order is a common requirement for reports

287 Using Slicers for Sort Order
This solution requires parameter tables They are disconnected and used only to support the slicer

288 Exercise 7-6: Slicers for Sort Order
Task 1: Have the students add the two parameter tables to the data model and show them the functions that the slicer will use and have already been created. Task 2: Have the students create the three measures that will build the foundation for the solution. Task 3: Have the students create functions that will calculate the values to be displayed in the PivotTable based on the value selected in the slicer. These two function will return the same value when added to the PivotTable and that is expected. The “Hidden” column will be hidden from the client tolls. It is there to determine the correct sort order of the rows.

289 Stale Dates in Slicers For reports that need to be kept up to date, old dates in slicers can be a headache You can design reports that can always be filtered to the most recent dates

290 Stale Dates in Slicers As always there is set-up required
In this case you would create a builder column in the date table that calculates if a date is within the last 15 days or is the most current =IF( Dates[Date]=MAX(Dates[Date]), "Latest" , IF( Dates[Date] < MAX(Dates[Date])-15, "Older" , FORMAT([Date], "mm/d/yyyy“ )))

291 Exercise 7-7: Current Date Slicers
Task 1: Have the students create a calculated column that will return the date for the last 15 day and then group all other days under a heading called Older. Task 2: Have the students add new sales and order dates to test the functionality of the slicer and ensure that it is updating when the data updates.

292 DAX Dashboard Techniques
Parameter Tables Banding Ranking Initializing Slicers Symbol Slicers Slicers for Sort Order Current Date Slicers Any Questions?

293 Course Review Basic DAX Functionality Controlling Content & Values
Context Control Functions Contexts in Relationships Advanced DAX Concepts Time Intelligence Calculations Bonus Content: DAX Dashboard Techniques

294 Online Resources Great DAX resource! www.powerpivotpro.com
Great Excel based reference!


Download ppt "Power BI for Excel DAX Functions"

Similar presentations


Ads by Google