Sub topic 2
Variables and DIVIDE for Readable, Safe Measures
Assume you know basic DAX measures, star-schema relationships, and how to place a measure in a Power BI visual. These measures assume a contiguous, marked Date table related to Sales[Order Date].
Variables and `DIVIDE`
Variables give a measure named intermediate results. They make repeated expressions easier to read and debug. DIVIDE handles a zero or blank denominator by returning blank instead of an error.
Total Sales = SUM ( Sales[Sales Amount] )
Sales PY =
CALCULATE (
[Total Sales],
SAMEPERIODLASTYEAR ( 'Date'[Date] )
)
Sales YoY % =
VAR CurrentSales = [Total Sales]
VAR PriorSales = [Sales PY]
RETURN
DIVIDE ( CurrentSales - PriorSales, PriorSales )The measure calculates the difference from the prior year, then divides that difference by prior-year sales. If no prior-year sales exist, the result is blank.
Year to Date
Year to date (YTD) means the total from January 1 through the last date in the current filter context. TOTALYTD is a convenient form of CALCULATE with DATESYTD.
Sales YTD =
TOTALYTD ( [Total Sales], 'Date'[Date] )
Sales YTD (CALCULATE) =
CALCULATE (
[Total Sales],
DATESYTD ( 'Date'[Date] )
)Both measures produce the same result when the date table is configured correctly.
Prior Year Comparison
SAMEPERIODLASTYEAR replaces the current dates with the corresponding dates one year earlier. DATEADD can express the same one-year shift.
Sales PY (DATEADD) =
CALCULATE (
[Total Sales],
DATEADD ( 'Date'[Date], -1, YEAR )
)Use the current visual context to control the comparison. For example, a matrix row for March 2025 evaluates the prior-year measure for March 2024.
Year-over-Year Growth
Year-over-year growth compares the current result with the prior-year result. Use DIVIDE so the measure remains safe when prior-year sales are blank or zero.
Exercise
What should Sales YoY % return when PriorSales is zero?
Show answer
DIVIDE returns blank by default, avoiding a division-by-zero error.