Forum Discussion
VAR and SWITCH Output issues
- 4 months ago
Hi Help_me
The logic inside your SWITCH statement is actually perfectly structured. The reason your code is failing and skipping down to the individual mappings is due to a hidden DAX mechanic inside your HasA and HasB variables called Context Transition.
Because you are writing a Calculated Column, DAX evaluates the formula row by row (a Row Context). Whenever you use the CALCULATE function inside a Row Context, DAX performs a "context transition," which automatically converts the current row into a filter. This means CALCULATE silently applies a filter for every single column in that specific row. If the current row has an action of "B", DAX restricts the table to that specific row and then tries to apply your snapshot[action] = "A" filter. Because a row cannot be both "A" and "B" at the same time, COUNTROWS returns 0, meaning HasA evaluates to FALSE.
Try out this DAX
New Action = VAR CurrentProject = snapshot[project_Num] VAR CurrentDate = snapshot[date] VAR HasA = CALCULATE( COUNTROWS(snapshot), ALL(snapshot), -- Overrides context transition to scan the whole table snapshot[project_Num] = CurrentProject, snapshot[date] = CurrentDate, snapshot[action] = "A" ) > 0 VAR HasB = CALCULATE( COUNTROWS(snapshot), ALL(snapshot), -- Overrides context transition to scan the whole table snapshot[project_Num] = CurrentProject, snapshot[date] = CurrentDate, snapshot[action] = "B" ) > 0 RETURN SWITCH( TRUE(), -- If both A and B exist on same date for the same project snapshot[action] IN {"A","B"} && HasA && HasB, "Cheese/Crackers", -- Individual mappings snapshot[action] = "A", "Cheese", snapshot[action] = "B", "Crackers", snapshot[action] = "X", "Water", snapshot[action] = "Y", "Cookie", BLANK() )If this solves your problem, please mark this as solved and give a kudos.
meso that i don't lose this thread.
Hi Help_me
Issue is context transition inside CALCULATE. HasA and HasB are not evaluating within current row context so they can override intended condition.
Can you try using ALLEXCEPT to fix filter context so the check is done only for the same project_Num and date.
New Action =
VAR HasA =CALCULATE(COUNTROWS(snapshot),ALLEXCEPT(snapshot, snapshot[project_Num], snapshot[date]),snapshot[action] = "A") > 0
VAR HasB = CALCULATE(COUNTROWS(snapshot), ALLEXCEPT(snapshot, snapshot[project_Num], snapshot[date]),snapshot[action] = "B") > 0
RETURN
SWITCH(TRUE(),snapshot[action] IN {"A","B"} && HasA && HasB, "Cheese/Crackers",snapshot[action] = "A", "Cheese",snapshot[action] = "B", "Crackers",snapshot[action] = "X", "Water",snapshot[action] = "Y", "Cookie", BLANK())