Search code examples
powerbidax

PowerBI Dax SWITCH Function does not give the same answer as IF Function


I'm trying to do use a SWITCH function instead of IF function.

I'm trying to search multiple columns (Column[1], Column[2]) within same sheet to return the value if it matches.

When using SWITCH, column 8 does not have the values 00,01,02, the code does not run through all the expression, instead just provides the result as blank. But i want to force the code to run through all the columns listed even if it faced a blank at the beginning. This is the original code with if statements:

Old code

test = 
    IF(Column[8]="O0", "O0",
    IF(Column[8]="O1", "O1",
    IF(Column[8]="O2", "O2",
    IF(Column[7]="O1", "O1",
    IF(Column[7]="O4", "O4",
    IF(Column[7]="O5", "O5",
    IF(Column[6]="O0", "O0",
    IF(Column[6]="O1", "O1",
    IF(Column[6]="O2", "O2",
    " " )

New code

test = SWITCH(
        Column[8],
          "O0", "O0",
          "O1", "O1",
          "O2", "O2",
        Column[7],
          "O1", "O1",
          "O4", "O4",
          "O5", "O5",
        Column[6],
          "O0", "O0",
          "O1", "O1",
          "O2", "O2",
        " "
       )

Solution

  • That's not how the DAX SWITCH statement works. You cannot switch the parameter mid-way through, however, you can use SWITCH( TRUE(), ... ).

    test = SWITCH( TRUE(),
      Column[8] = "O0", "O0",
      Column[8] = "O1", "O1",
      Column[8] = "O2", "O2",
    
      Column[7] = "O1", "O1",
      Column[7] = "O4", "O4",
      Column[7] = "O5", "O5",
    
      Column[6] = "O0", "O0",
      Column[6] = "O1", "O1",
      Column[6] = "O2", "O2",
    
      " "
    )
    

    If you are interested, you can simplify the above with:

    test = SWITCH( TRUE(),
      Column[8] IN { "O0", "O1", "O2" }, Column[8],
      Column[7] IN { "O1", "O4", "O5" }, Column[7],
      Column[6] IN { "O0", "O1", "O2" }, Column[6],
      " "
    )