Sub topic 5
Variables and DIVIDE for readable, safe measures
This chapter assumes you can write basic measures with SUM, know what a star schema is, and have a Date table related to a Sales fact table. It also assumes you know a measure is re-evaluated for every cell of a visual. The next chapters build year-over-year growth and moving averages, and both depend on the two tools covered here: VAR and DIVIDE.
Why these two tools matter for time intelligence
A time intelligence measure usually combines several pieces: a current value, a shifted value, and a calculation between them. Written as one expression, it repeats the same sub-expressions and is hard to read. It can also return errors or Infinity for periods with no history, such as the first year of data.
VARnames an intermediate result so you compute it once and reuse it.DIVIDEhandles a zero or blank denominator without an error.
The examples below use these base measures:
Total Sales = SUM ( Sales[Sales Amount] )
Sales PY =
CALCULATE ( [Total Sales], SAMEPERIODLASTYEAR ( 'Date'[Date] ) )Variables with VAR and RETURN
A variable is declared with VAR, given a name, and assigned an expression. Every measure that uses VAR must finish with RETURN, which gives the final result.
Sales YoY Change =
VAR CurrentSales = [Total Sales]
VAR PriorSales = [Sales PY]
RETURN
CurrentSales - PriorSalesYou can declare as many variables as you need. A later variable can use an earlier one, but not the other way around.
Sales Above Prior Year Flag =
VAR CurrentSales = [Total Sales]
VAR PriorSales = [Sales PY]
VAR Change = CurrentSales - PriorSales
RETURN
IF ( Change > 0, "Up", "Down or flat" )Variables help in three ways:
- Readability. Names such as
PriorSalesexplain the intent. A reader does not have to decode a nestedCALCULATE. - Performance. A variable is evaluated once, even if you reference it several times. Without a variable,
[Sales PY]would be written out each time it appears. - Debugging. You can change
RETURNto show any variable. This lets you inspect each step in a table visual.
A variable can hold a scalar value, as above, or a whole table. The moving-average measures later in the tutorial store a table of dates in a variable called Window.
The rule that trips people up: variables are fixed where they are defined
A variable is evaluated in the filter context that exists where the VAR line sits. After that its value is a constant. If you later use it inside CALCULATE, the new filters do not change it.
This measure looks like a prior-year calculation, but it is not:
Sales PY Wrong =
VAR CurrentSales = [Total Sales]
RETURN
CALCULATE ( CurrentSales, SAMEPERIODLASTYEAR ( 'Date'[Date] ) )CurrentSales was already computed for the current dates. CALCULATE shifts the date filter, but the value inside it is already a number, so the measure returns the current-period total in every cell. The fix is to put the CALCULATE inside the variable:
Sales PY Right =
VAR PriorSales =
CALCULATE ( [Total Sales], SAMEPERIODLASTYEAR ( 'Date'[Date] ) )
RETURN
PriorSalesUse this rule when deciding where to place a variable: if the value must be computed under a different date filter, the CALCULATE that changes the filter belongs in the variable's definition.
A table variable behaves differently, because you can pass it into CALCULATE as a filter. Here the variable holds the dates, and CALCULATE applies them. That is how Sales 3 Month Avg in a later chapter works.
Two smaller points:
- Variables are scoped to the measure. Two measures can each have a
VAR CurrentSaleswithout conflict. - A variable name cannot match a table name in the model. Names like
WindoworLastDateare safe, and a name likeSalesis risky because you have aSalestable.
DIVIDE: safe division
The / operator fails in awkward ways. Dividing by zero gives Infinity, and 0 / 0 gives NaN. Dividing by a blank also gives Infinity. Both show up as ugly values in visuals and can distort axis scales.
DIVIDE takes a numerator, a denominator, and an optional alternate result:
DIVIDE ( numerator, denominator [, alternateResult] )If the denominator is zero or blank, DIVIDE returns alternateResult. If you leave that argument out, it returns BLANK.
| Expression | Result |
|---|---|
| `10 / 0` | `Infinity` |
| `0 / 0` | `NaN` |
| `DIVIDE ( 10, 0 )` | blank |
| `DIVIDE ( 10, 0, 0 )` | `0` |
| `DIVIDE ( 10, BLANK () )` | blank |
| `DIVIDE ( 10, 4 )` | `2.5` |
Blank or zero as the alternate result?
Prefer the default, which is blank. Power BI visuals leave out rows and points where the measure is blank. In a prior-year growth measure, a blank means "there is nothing to compare against", which is accurate. A zero would say "growth was exactly 0%", which is false.
Use an alternate value only when the business definition requires it. A ratio that must show 0 in a scorecard is one case. Even then, be aware that zeros make every row appear in a matrix, including rows with no data.
Putting them together: year-over-year growth
This is the measure from the plan for this tutorial. It uses both tools:
Sales YoY % =
VAR CurrentSales = [Total Sales]
VAR PriorSales = [Sales PY]
RETURN
DIVIDE ( CurrentSales - PriorSales, PriorSales )Follow it through three cases:
- Normal year. Current is 120 and prior is 100. The result is
DIVIDE ( 20, 100 ), which is0.2. Format the measure as a percentage to show 20%. - First year of data. Prior is blank. Subtracting a blank treats it as zero, so the numerator is 120. The denominator is blank, so
DIVIDEreturns blank. Without it you would seeInfinity. - No sales this year. Current is blank and prior is 100. The numerator is
-100, so the result is-1, or -100%. This is correct if the business really sold nothing. In a future period it is wrong, and the chapter on blanking incomplete periods shows how to handle that.
Each variable is computed once, and PriorSales appears twice in the final expression. With the RETURN line replaced by PriorSales, you can check the shifted value on its own before trusting the ratio.
Debugging a measure by returning variables
When a measure gives an unexpected number, return each variable in turn. A temporary copy of the measure works well:
Sales YoY % Debug =
VAR CurrentSales = [Total Sales]
VAR PriorSales = [Sales PY]
VAR Result = DIVIDE ( CurrentSales - PriorSales, PriorSales )
RETURN
ResultChange the last line to CurrentSales, then PriorSales, and compare each against a plain table of the sales by year. Whichever step first disagrees with your expectation is the step to fix. You can also return a text value that combines several variables, such as FORMAT ( CurrentSales, "#,0" ) & " vs " & FORMAT ( PriorSales, "#,0" ), to see both side by side in one cell.
Common mistakes
- Putting the filter change outside the variable. See
Sales PY Wrongabove. - Using
/on a prior-period denominator. The first period showsInfinityor an error. - Using
DIVIDE ( a, b, 0 )everywhere. Rows with no data now appear as zeros and clutter visuals. - Forgetting
RETURN. The measure fails to compile. - Repeating
[Sales PY]inline several times. This works, but it is harder to read and easy to edit in one place and not the others.
Exercise
A colleague writes this measure and finds that it equals Total Sales in every cell, even though the visual has years on rows. What is wrong, and how do you fix it? Sales PY Check = VAR CurrentSales = [Total Sales] RETURN CALCULATE ( CurrentSales, SAMEPERIODLASTYEAR ( 'Date'[Date] ) )
Show answer
CurrentSales is evaluated in the current filter context where the VAR is defined, so it is already a fixed number when CALCULATE runs. CALCULATE cannot change it. Move the date shift into the variable: VAR PriorSales = CALCULATE ( [Total Sales], SAMEPERIODLASTYEAR ( 'Date'[Date] ) ) and then RETURN PriorSales.
Exercise
In the first year of data, Sales YoY % is defined as DIVIDE ( CurrentSales - PriorSales, PriorSales ). What does the visual show for that year, and why is that preferable to using the / operator?
Show answer
It shows a blank, because PriorSales is blank and DIVIDE returns BLANK when the denominator is zero or blank. The / operator would return Infinity, which displays badly and can distort chart scales. A blank also correctly says there is no comparison, where 0% would claim no growth.