Power BI for Excel DAX Functions

Slides:



Advertisements
Similar presentations
Introduction to Excel Formulas, Functions and References.
Advertisements

Tutorial 5: Working with Excel Tables, PivotTables, and PivotCharts
Mgt 240 Lecture MS Excel and Access: Introduction to Databases September 23, 2004.
DAX uses a syntax similar to Excel TableX [ColY] or [ColY] (fully qualified vs. not qualified) Cells cannot be referenced (like B23, B12:C15, …)
Access 2007 ® Use Databases How can Access help you to find and use information?
MS Access: Database Concepts Instructor: Vicki Weidler.
Database Applications – Microsoft Access Lesson 9 Designing Special Queries Updated 4/11.
Database Applications – Microsoft Access Lesson 9 Designing Special Queries.
CHAPTER 13 Creating a Workbook Part 2. Learning Objectives Work with cells and ranges Work with formulas and functions Preview and print a workbook 2.
Objects for Business Reporting MIS 497. Objective Learn about miscellaneous objects required for business reporting. Learn about miscellaneous objects.
XP. Objectives Sort data and filter data Summarize an Excel table Insert subtotals into a range of data Outline buttons to show or hide details Create.
Chapter 5 Working with Multiple Worksheets and Workbooks
Microsoft Excel 2013 Chapter 8 Working with Trendlines, PivotTable Reports, PivotChart Reports, and Slicers.
1Copyright © 2011 Pearson Education, Inc. Publishing as Prentice Hall. Exploring Microsoft Office Access 2010 by Robert Grauer, Keith Mast, and Mary Anne.
Aggregator Stage : Definition : Aggregator classifies data rows from a single input link into groups and calculates totals or other aggregate functions.
Microsoft ® Excel ® 2013 Enhanced Tutorial 5: Working with Excel Tables, PivotTables, and PivotCharts.
Pages Appendix B: Review of ExcelChapter 3 Market Trends & Analysis IBM 320 CAL POLY POMONA IBM320 Market Trends and Analysis Maha Ghosn.
Example Materials Power BI Desktop File (4/16): 6WPbWY5UTRhaHYwdDA/view?usp=sharing.
about me – Austin Senseman, CFA 5 years in Financial Services, Managed analytics for sales, marketing, risk, finance, &
SJSU College of Business Business Productivity Tools Fall 2016 Summary of Lessons and Learning Objectives.
John Tran Business Program Manager, The Suddath Companies
Overview Rental Quote Overview
Product Training Program
The Little man computer
AP CSP: Cleaning Data & Creating Summary Tables
Copyright © Bird Media LLC
Creating Oracle Business Intelligence Interactive Dashboards
Excel Functions.
Operation Data Analysis Hints and Guidelines
Microsoft Excel.
Chelsea Dohemann Class will start at approximately 8:10am PowerPivot Chelsea Dohemann
Tutorial 5: Working with Excel Tables, PivotTables, and PivotCharts
Copyright © Bird Media LLC
Loops BIS1523 – Lecture 10.
Statistical Analysis with Excel
REACH Computer Resource Center
Cross UG Summit EMEA /6/2018 7:24 PM
Module 11: Introduction to DAX Module 11 Introduction to DAX
The Price IS Right: What can the billing module do for me?
Topics Introduction to Repetition Structures
Microsoft Excel 2003 Illustrated Complete
Formatting a Workbook Part 2
While Loops BIS1523 – Lecture 12.
Creating a Workbook Part 2
Statistical Analysis with Excel
Designing and Debugging Batch and Interactive COBOL Programs
Unit# 9: Computer Program Development
MODULE 7 Microsoft Access 2010
Creating and Modifying Queries
Statistical Analysis with Excel
Number and String Operations
SSI Toolbox Status Workbook Overview
Please use speaker notes for additional information!
Navya Thum February 13, 2013 Day 7: MICROSOFT EXCEL Navya Thum February 13, 2013.
Java Programming Arrays
Java Programming Loops
Welcome ! Excel 2013/2016 Data Consolidation (Lab Format)
Evaluation Context Concepts and Examples.
Microsoft Official Academic Course, Access 2016
Exploring Microsoft® Office 2016 Series Editor Mary Anne Poatsy
Boolean Expressions to Make Comparisons
Topic 8 – Pivot tables and Charts Lesson 1 – Pivot tables
Topic 11 Lesson 1 - Analyzing Data in Access
Introduction to Excel 2007 Part 3: Bar Graphs and Histograms
Software Development Techniques
REACH Computer Resource Center
Presentation transcript:

Power BI for Excel DAX Functions Your Instructor: Michelle Metzger

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 1-800-460-2298 or email Clientcontact@TLGLearning.com

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.

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

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

Unit 1: Basic DAX Functionality

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

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

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

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.

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

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

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

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

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

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

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

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

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

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

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.

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]))

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

Unit 2: Controlling Content & Values

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

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

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).

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

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).

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.

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” )

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.

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

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

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”

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

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

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.

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

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.

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.

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

Unit 3: Context Control Functions

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

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.

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.

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

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

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

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.

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] ) )

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

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.

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.

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.

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

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

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

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.

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] ) )

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

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.

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.

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

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.

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.

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

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.

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.

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

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

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

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

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

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.

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

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

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 )

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)

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

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

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

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

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.

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

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 ) )

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]) )

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.

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

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 >

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

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!

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

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

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.

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

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” )

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

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 >

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

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.

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.

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

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.

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.

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

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.

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.

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

Unit 4: Contexts In Relationships

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

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

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

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.

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.

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

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

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

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.

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

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

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

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

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

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

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])

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.

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

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.

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

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

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

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.

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.

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

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

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

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

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

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.

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.

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

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

Unit 5: Advanced Concepts

5. Advanced Concepts Circular Dependencies Controlling Totals Advance Hierarchy Concepts

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

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

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

Exercise 5-1: Circular Dependencies Task 1:

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

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]))

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)

Exercise 5-2: Circular Dependencies Task 1:

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

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

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() )

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

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.

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?

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

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() )

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

ISFILTERED Notice that applying the function has resolved this issue!

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

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

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

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

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

Exercise 5-3: Controlling Totals Task 1:

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

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?

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

Exercise 5-4: Multi-Table Hierarchies

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

Unit 6: Time Intelligence Calculations

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

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

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

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

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

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.

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

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

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 )

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

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

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!

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] )

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.

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

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.

> 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

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,452.32 / 248 = $2,816.34

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.

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

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.

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

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!!!

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

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

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

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.

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

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

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

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

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

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

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.

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.

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

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]) )

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]) )

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

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.

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.

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

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]) )

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] ) ) )

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.

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

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( )

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.

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.

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

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

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.

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 )

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 )

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 )

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

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

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

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

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.

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 ]

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.

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

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.

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

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

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] )

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

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)

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 ) ) )

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]) )

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 ) ) )

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 )

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) )

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> )

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

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.

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

Bonus Content: DAX Dashboard Techniques

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

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

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

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

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

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.

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

Banding A weather map is broken into bands by temperature.

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

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

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.

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

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] ) )

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.

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

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

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

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

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

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

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

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.

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

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!!

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

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:

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

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

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

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

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.

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

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

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.

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

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“ )))

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.

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

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

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