08.2The order of variables

A variable can be used to calculate the next one. The order in which you write them then decides whether the formula works.

08.2.1Reusing a variable

A variable can use a variable written before it:

Average Price = VAR TotalRevenue = SUM( Sales[Amount] ) VAR Quantity = SUM( Sales[Qty] ) VAR Price = DIVIDE( TotalRevenue, Quantity ) RETURN Price
Power BI accepts this DAX foryes, Measureyes, Calculated columnno, Calculated tableno, Virtual table

“Price” uses “TotalRevenue” and “Quantity,” written above it. The formula works.

08.2.2A variable exists only after its line

Watch out!

A variable cannot use a variable written after it:

Average Price = VAR Price = DIVIDE( TotalRevenue, Quantity ) VAR TotalRevenue = SUM( Sales[Amount] ) VAR Quantity = SUM( Sales[Qty] ) RETURN Price

Power BI reads the VAR lines from top to bottom, and each variable is known only once its line is passed. On the line of “Price,” “TotalRevenue” and “Quantity” don’t exist yet, so Power BI reports an error.

Quiz

The questions often rely on the course tables. Keep them in view in their floating window, which you can move and enlarge.

Question 1

You want a measure that returns the New York share. You first write VAR TotalRevenue, then VAR Share = DIVIDE( NewYorkRevenue, TotalRevenue ), and only after that VAR NewYorkRevenue. What happens?

Question 2

The variable VAR Price = DIVIDE( TotalRevenue, Quantity ) uses two other variables, “TotalRevenue” and “Quantity.” In which order should you write the three VAR lines?

Question 3

On a card with no filter at all, what does the measure VAR TotalRevenue = SUM( Sales[Amount] ) VAR SalesCount = COUNTROWS( Sales ) VAR CustomerCount = DISTINCTCOUNT( Sales[Customer ID] ) VAR RevenuePerCustomer = DIVIDE( TotalRevenue, CustomerCount ) RETURN RevenuePerCustomer return?

Key takeaways
  • A variable can use the variables written before it.
  • A variable exists only after its VAR line, and using it higher up causes an error.