C O M P 2 1 5 6 :
INTRO TO POWER BI
LECTURE 3
Agenda
Introduction to DAX (Data Analysis Expressions)
o Calculated Columns vs. Measures
o Quick Measures
o Building blocks of DAX & Most commonly used DAX
Time-Intelligence with DAX and leveraging your Date Table
Mastering DAX Tips
DAX !
Calculated Columns
vs.
Measures
What’s DAX?
DAX is an acronym for Data Analysis Expressions, it is the language you use to compute a variety of
functions in Power BI.
There are 2 ways to write DAX:
1. Using Calculated Columns
2. Using Measures
Calculated Columns
- Adds a column to a table within your data
set (your data model gets larger)
- Best used in categorizing your data and not
in computing numerical values (such as
totals, averages etc.)
Ex. If a column lists number of children, and you
want to identify parents vs. non-parents. You
can use a calculated column to separate these
people. (i.e. IF “number of children” = 0 THEN
person is not a parent; IF “number of children” >
0 THEN person is a parent
Measures
- Does not add data to your data model
- Best used for calculating numerical values
- Almost always used in the “Values” field
within the visualizations pane
Notice the calculator
icon, this tells you
these are measures
Creating Calculated Columns & Measures
Option 2: Create in “Report” view
Option 1: Create in “Data” view
Option 3: Create in “Home” taskbar
Calculated Columns
Measures
Calculated columns generate values for
each row, which are visible within tables in
the Data view
Unlike calculated columns, measure values
aren’t visible within tables; they can only be
“seen” within a visualization like a chart or
matrix (similar to a calculated field in an
Excel pivot)
DO NOT use calculated columns for
aggregation formulas, or to calculate fields
for the “Values” area of a visualization (use
measures instead)
Appends static values to each row in a
table and stores them in the model (which
increases file size)
As a rule of thumb, use measures (vs.
calculated columns) when a single row
can’t give you the answer (in other words,
when you need to aggregate)
Use measures to create numerical,
calculated values that can be analyzed in
the “values” field of a report visual
Quick Measures
Quick Measures
Quick Measures are pre-built
formula templates that allow
you to drag and drop fields,
rather than write DAX from
scratch.
While these tools can be helpful
for defining more complex
measures (like weighted
averages or time intelligence
formulas), they encourage
laziness and don’t help you
understand the fundamentals
of DAX
Implicit vs. Explicit Measures
• Implicit measures are created when you drag raw
numerical fields (like “OrderQuantity”) into the values
pane of a visual and manually select the aggregation
mode (Sum, Average, Min/Max, etc)
• Explicit measures are created by actually entering
DAX functions (or adding “quick measures”) to define
calculated columns or measures
Implicit measures are only accessible within the
specific visualization in which it was created,
and cannot be referenced elsewhere
Explicit measures can be used anywhere in the
report, and referenced within other DAX
calculations to create “measure trees”
Building blocks of
DAX
&
Most Commonly
Used DAX
How to speak DAX
Tip
When entering DAX formulas in Power BI Desktop, you have the benefit of IntelliSense. IntelliSense is a code-completion aid that lists functions
and model resources. When you select a DAX function, it also provides you with a definition and description. We recommend that you use
IntelliSense to help you quickly build accurate formulas.
Logical Operators
ARITHMETIC OPERATORS
Operator
Description
Operator
Description
+
Addition
&&
-
Subtraction
*
Multiplication
/
Division
^
Exponentiation
Creates an AND condition between
two expressions where each has a
Boolean result. If both expressions
return TRUE, the combination of the
expressions also returns TRUE;
otherwise the combination returns
FALSE.
|| (double pipe)
Creates an OR condition between
two logical expressions. If either
expression returns TRUE, the result is
TRUE; only when both expressions are
FALSE is the result FALSE.
IN
Creates a logical OR condition
between each row that is being
compared to a table. Note: The table
constructor syntax uses braces.
NOT
Inverts the state of a Boolean
expression (FALSE to TRUE, and vice
versa).
Comparison Operators
Operator
Description
=
Equal to
==
Strict equal to
>
Greater than
<
Less than
>=
Greater than or equal to
<=
Less than or equal to
<>
Not equal to
How to speak DAX (cont’d)
Date & Time Functions
Function
Definition
Application
DAY/MONTH/ YEAR()
Returns the day of the month (1-31), month of the
year (1-12), or year of a given date
=DAY/MONTH/YEAR(Date)
HOUR/MINUTE/ SECOND()
Returns the hour (0-23), minute (0-59), or second
(0-59) of a given datetime value
=HOUR/MINUTE/SECOND(Datetime)
TODAY/NOW()
Returns the current date or exact time
=TODAY/NOW()
WEEKDAY/ WEEKNUM()
Returns a weekday number from 1 (Sunday) to 7
(Saturday), or the week # of the year
=WEEKDAY/WEEKNUM(Date, [ReturnType])
EOMONTH()
Returns the date of the last day of the month, +/a specified number of months
=EOMONTH(StartDate, Months)
DATEDIFF()
Returns the difference between two dates, based
on a selected interval
=DATEDIFF(Date1, Date2, Interval)
Date & Time DAX:
Navigate to the Data Tab
Go to your Calendar/Date Table ‘AW_Calendar_Lookup’
Right click anywhere in your table and add a new column
Day of Week =
WEEKDAY(AW_Calendar_Lookup[Date],2)
Go to the ‘AW_Customer_Lookup’
Demo
Right click anywhere in your table and add a new column
BirthYear =
YEAR(AW_Customer_Lookup[BirthDate])
OR
BirthYear =
AW_Customer_Lookup[BirthDate].[Year]
Go to the ‘AW_Customer_Lookup’
Right click anywhere in your table and add a new column
Current Age =
DATEDIFF(AW_Customer_Lookup[BirthDate],TODAY(),[Year])
Basic logical functions (IF/AND/OR)
Function
Definition
Application
IF
Checks a condition, and returns one value when
it's TRUE, otherwise it returns a second value.
=IF(LogicalTest, ResultIfTrue, [ResultIfFalse])
IFERROR
Evaluates an expression and returns a specified
value if the expression returns an error
=IFERROR(Value, ValueIfError)
AND
Checks whether both arguments are TRUE, and
returns TRUE if both arguments are TRUE.
=AND(Logical1, Logical2)
OR
Checks whether one of the arguments is TRUE to
return TRUE.
=OR(Logical1, Logical2)
Note: Use the && and || operators if you want
to include more than two conditions!
Conditional & Logical Functions:
Navigate to the Data View
Go to the ‘AW_Customer_Lookup’
Right click anywhere in your table and add a new column
Parent =
IF (AW_Customer_Lookup[TotalChildren] > 0, “Yes”, “No”)
Go to your Calendar/Date Table ‘AW_Calendar_Lookup’
Demo
Right click anywhere in your table and add a new column
Weekend =
IF (OR(AW_Calendar_Lookup[Day of Week] = 6,
AW_Calendar_Lookup[Day of Week] = 7), “Weekend” , “Weekday” )
OR
Weekend =
IF (AW_Calendar_Lookup[Day of Week] = 6 ||
AW_Calendar_Lookup[Day of Week] = 7 , “Weekend” , “Weekday” )
RELATED Function:
Allows you to pull columns in from other tables where the table in question has a
relationship with the other one.
Navigate to the Data View
Go to the ‘AW_Sales’
Right click anywhere in your table and add a new column
Retail_Price =
RELATED (AW_Product_Lookup[ProductPrice])
Demo
Then in the Modeling tab change the format to $ English (United States)
Go to the ‘AW_Sales’
Right click anywhere in your table and add a new column
Revenue =
AW_Sales[Retail_Price] * AW_Sales[OrderQuantity]
Basic Math & Stats Functions
Function
Definition
Application
SUM
Evaluates the sum of a column
=SUM(ColumnName)
AVERAGE
Returns the average (arithmetic mean) of all the
numbers in a column
=AVERAGE(ColumnName)
MAX
Returns the largest value in a column or between
two scalar expressions
=MAX(ColumnName) or =MAX(Scalar1, [Scalar2])
MIN
Returns the smallest value in a column or
between two scalar expressions
=MIN(ColumnName) or =MIN(Scalar1, [Scalar2])
DIVIDE
Performs division and returns the alternate result
(or blank) if div/0
=DIVIDE(Numerator, Denominator,
[AlternateResult])
Basic Math & Stats Function:
Navigate to the Report View
Go to the ‘AW_Returns’ & ‘AW_Sales’
Right click and create a new measure
Quantity Returned =
SUM (AW_Returns[ReturnQuantity])
Total Revenue =
Demo
SUM (AW_Sales[Revenue])
Return Rate =
DIVIDE ( [Quantity Returned] , [Quantity Sold] , “No Sales” )
Avg Retail Price =
AVERAGE ( AW_Sales[Retail Price] )
Then in the Modeling tab change the format to $ English (United States)
COUNT, COUNTA, DISTINCTCOUNT & COUNTROWS
Function
Definition
Application
COUNT
Counts the number of cells in a column that contain
numbers
=COUNT(ColumnName)
COUNTA
Counts the number of non-empty cells in a column
(numerical and non-numerical)
=COUNTA(ColumnName)
DISTINCTCOUNT
Counts the number of distinct or unique values in a
column
=DISTINCTCOUNT(ColumnName)
COUNTROWS
Counts the number of rows in the specified table, or a
table defined by an expression
=COUNTROWS(Table)
COUNT Functions:
Navigate to the Report View
Go to the ‘AW_Returns’
Right click and create a new measure
Total Returns =
COUNTROWS( AW_Returns )
Go to the ‘AW_Sales’
Demo
Right click and create a new measure
Total Orders =
DISTINCTCOUNT (AW_Sales[OrderNumber] )
The Most Powerful DAX Function
CALCULATE
=CALCULATE(Expression, [Filter1], [Filter2],…)
Name of an existing measure, or a DAX
formula for a valid measure Examples:
• [Total Orders]
• SUM(Returns_Data[ReturnQuantity])
List of simple Boolean (True/False) filter expressions
(note: these require simple, fixed values; you cannot
create filters based on measures) Examples:
• Territory_Lookup[Country] = “USA”
• Calendar[Year] > 1998
CALCULATE Functions:
Navigate to the Report View
Go to the ‘AW_Sales’
Right click and create a new measure
Weekend Orders =
CALCULATE ( [Total Orders],
Demo
AW_Calendar_Lookup[Weekend] = “Weekend” )
High Ticket Orders =
CALCULATE ( [Total Orders],
FILTER ( AW_Product_Lookup,
AW_Product_Lookup[ProductPrice] > [ Overall Avg Price] ))
Best Practices: DAX
• Eliminate redundant columns; keep data tables narrow
Data tables should ideally only contain only quantitative values and foreign keys; any extra descriptive columns
can usually live in a related lookup table Imported columns are better than calculated columns
• Imported columns are better than calculated columns
When possible, create calculated columns at the source (i.e. in your raw database) or within the Query Editor; this
is more efficient than processing those calculations in the Data Model Minimize iterator functions (FILTER, SUMX,
etc.)
• Minimize iterator functions (FILTER, SUMX, etc.)
Functions that cycle through each row in a table are “expensive”, meaning that they take time and consume
processing power
• In general, use Measures instead of Calculated Columns
You don’t want unnecessary data in your report, it will slow it down and its a pain for your end users.
•
Breakdown complex DAX equations into small manageable functions which you can combine
Take baby steps, DAX takes lots of practice. Many who are proficient at Power BI still struggle and often refer to
textbooks for support.
•
Use a measure table to keep all your measures in one central place
Time-Intelligence
with DAX
&
leveraging your
Data Table
Time Intelligence Functions
Date table requirement
To work with time intelligence DAX functions, you need to meet the prerequisite model requirement of
having at least one date table in your model. A date table is a table that meets the following requirements:
• It must have a column of data type Date (or date/time), known as the date column.
• The date column must contain unique values.
• The date column must not contain BLANKs.
• The date column must not have any missing dates.
• The date column must span full years. A year isn't necessarily a calendar year (January-December).
• The date table must be indicated as a date table.
Summarizations over time
One group of DAX time intelligence functions is concerned with summarizations over time:
•
DATESYTD DAX function - Returns a single-column table that contains dates for the year-to-date (YTD) in the current filter context. This
group also includes the DATESMTD and DATESQTD DAX functions for month-to-date (MTD) and quarter-to-date (QTD). You can pass
these functions as filters into the CALCULATE DAX function.
•
TOTALYTD DAX function - Evaluates an expression for YTD in the current filter context. The equivalent QTD and MTD DAX functions of
TOTALQTD and TOTALMTD are also included.
•
DATESBETWEEN DAX function - Returns a table that contains a column of dates that begins with a given start date and continues until a
given end date.
•
DATESINPERIOD DAX function - Returns a table that contains a column of dates that begins with a given start date and continues for the
specified number of intervals.
Revenue YTD =
TOTALYTD([Revenue], 'Date'[Date], "6-30")
Comparisons over time
Another group of DAX time intelligence functions is concerned with shifting time periods:
•
DATEADD DAX function - Returns a table that contains a column of dates, shifted either forward or backward in time
by the specified number of intervals from the dates in the current filter context.
•
PARALLELPERIOD DAX function - Returns a table that contains a column of dates that represents a period that is
parallel to the dates in the specified dates column, in the current filter context, with the dates shifted a number of
intervals either forward in time or back in time.
•
SAMEPERIODLASTYEAR DAX function - Returns a table that contains a column of dates that are shifted one year
back in time from the dates in the specified dates column, in the current filter context.
Revenue YoY % =
VAR RevenuePriorYear = CALCULATE([Revenue],
SAMEPERIODLASTYEAR('Date'[Date]))
RETURN
DIVIDE(
[Revenue] - RevenuePriorYear,
RevenuePriorYear
)
Revenue PY =
VAR RevenuePriorYear = CALCULATE([Revenue],
SAMEPERIODLASTYEAR('Date'[Date]))
RETURN
RevenuePriorYear
Comparisons over time
Revenue PY
Revenue YoY %
Calculate new occurrences
Another use of time intelligence functions is to count new occurrences. The following example shows how you can
calculate the number of new customers for a time period. A new customer is counted in the time period in which
they made their first purchase.
Your first task is to add the following measure definition that counts the number of distinct customers life-todate (LTD). Life-to-date means from the beginning of time until the last date in filter context. Format the measure as a
whole number by using the thousands separator.
Customers LTD =
VAR CustomersLTD =
CALCULATE(
RETURN
)
DISTINCTCOUNT(Sales[CustomerKey]),
DATESBETWEEN(
'Date'[Date],
BLANK(),
MAX('Date'[Date])
),
'Sales Order'[Channel] = "Internet"
CustomersLTD
Calculate new occurrences
Next, you will modify the measure by renaming it to New Customers and by adding a second variable to store the
count of distinct customers before the time period in filter context. The RETURN clause now subtracts this value from
LTD customers to produce a result, which is the number of new customers in the time period.
New Customers =
VAR CustomersLTD =
CALCULATE(
)
VAR CustomersPrior =
CALCULATE(
RETURN
)
DISTINCTCOUNT(Sales[CustomerKey]),
DATESBETWEEN(
'Date'[Date],
BLANK(),
MAX('Date'[Date])
),
'Sales Order'[Channel] = "Internet"
DISTINCTCOUNT(Sales[CustomerKey]),
DATESBETWEEN(
'Date'[Date],
BLANK(),
MIN('Date'[Date]) - 1
),
'Sales Order'[Channel] = "Internet"
CustomersLTD - CustomersPrior
Time Intelligence Functions:
Navigate to the Report View
Go to the ‘AW_Sales’
Right click and create a new measure
YTD Revenue =
CALCULATE ( [Total Revenue] ,
Demo
DATESYTD ( AW_Calendar_Lookup [Date] ))
Prev Month Revenue =
CALCULATE ( [Total Revenue] ,
DATEADD ( AW_Calendar_Lookup [Date] , -1, MONTH ) )
•
-1 (One month in the past)
Revenue Target = [Prev Month Revenue] * 1.1
10-Day Rolling Revenue =
CALCULATE ( [Total Revenue] ,
DATESINPERIOD ( AW_Calendar_Lookup [Date] ,
MAX(AW_Calendar_Lookup [Date] ) , -10 , DAY ) )
Mastering
DAX
Tips
How to Master DAX?
Subscribe to this YouTube channel – great FREE tutorials
Go buy this book now! It’s totally worth it
How to Master DAX? (cont’d)
Ruth has great weekly segments on showing you how to do various analyses with DAX. Go check out
Curbal on YouTube.
Source: https://www.youtube.com/channel/UCJ7UhloHSA4wAqPzyi6TOkw
How to Master DAX? (cont’d)
Their forum is very active, if you
don’t know how to solve a
problem chances are someone
on this platform will!
Source: https://community.powerbi.com/
How to Master DAX? (cont’d)
Source: https://docs.microsoft.com/en-us/dax/dax-function-reference
THANK YOU
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )