Earlier this year, new version of DAX was released. One of the key features with this release is the support for variables. Variables makes writing DAX code easier. Variables also make code easier to read and understand.
Download sample data here. Data represents sales for a particular store. Products are categorized by seasonality and color. We want to calculate the % of in season product that are sold in the store. We can do this without using variables:
% In Season Sales = DIVIDE (CALCULATE(
Now let’s do the same using variables.
% In Season Sales (With Var) =
Notice we created two variables:
VAR InSeasonSales is used to calculate the sales of seasonal products.
VAR AllSales is used to calculate sales of the all the products.
And DIVIDE function is used to get the percentage.
Notice that creating variables made the code easy to read.
Let’s look at something a little more complex. We need to calculate percentage of Red in season products that are sold.
% In Season Red Sales =
VAR InSeasonSales =
Notice in this case, variables InSeasonRed and InSeasonSales has different filters. Writing them as variables makes this apparent and easy to read. As the measures get complex, using variables is a huge advantage to both write and read code.
Here are a few good references: