Warm tip: This article is reproduced from serverfault.com, please click

DAX: please check if I understood the use of Variabes in DAX correctly

发布于 2020-11-29 09:11:20

can someone please check if my theoretical understanding of variables is correct?

Suppose that I have a table with 2 columns, Condition1 and Condition2. I want to count the rows for which Condition1 = 4, and Condition2 = Black.

Soppose then that I write a measure called Black, that creates a Table where all rows have Condition2 = "Black". For Example:

Black:= FILTER (Table, Condition2 = "Black")

And then I write the combined code using variables:

Black4_version1 = 
var B = [Black]
return = CALCULATE(
COUNTROWS(B),
Condition1 = 4)

Then this code will not work because DAX thinks that the variable B is a single number (because it's calling a measure and measure is by default seen as a single value?), even though I have created a measure that should have created a table.

But if I create the table within a variable itself, then DAX will know that it's a table and then it will work?

Black4_Version2 = 
var B = FILTER (Table, Condition2 = "Black")
return = CALCULATE(
COUNTROWS(B),
Condition1 = 4)

I'm asking this because I want to be 100% sure that I have understood the answer given here: DAX: please explain why this measure with a variable will not work also because I have been using variables already at work, so I will need to re-check all the dashboards that I have built and talk to my manager about screwing up a big time. So you could say that my job depends on this.

Questioner
Lya
Viewed
0
sergiom 2020-11-29 18:27:49

Variables are to be considered constants even when they contain a table. In your Black4_Version2 measure, the CALCULATE() doesn't change the COUNTROWS(B) result, since it's counting the rows of a constant table and no filtering is happening.

Black4_Version2 =
VAR B =
    FILTER(
        Table,
        Condition2 = "Black"
    )
RETURN
    CALCULATE(
        COUNTROWS( B ),
        Condition1 = 4
    )

but you can iterate over a constant table, therefore FILTER works

Black4_Version3 =
VAR B =
    FILTER(
        Table,
        Condition2 = "Black"
    )
RETURN
    COUNTROWS(
        FILTER(
            B,
            Condition1 = 4
        )
    )

P.S. I used the pseudo-DAX sintax used in the answer, since instead of Condition1 = 4 a column reference like Table[Column1] = 4 should be used