I need to change the value of variables in a switch in dax:
switch( true(),
condition1,
var test1 = 2
var test2 = 3
,condition 2,
var test1 = 4
var test2 = 5
,
var test1 = 7
var test2 = 6
)
I need to do this because I have to change massive number of variables depending on the condition, and I don't want to have a switch for every single variable.
I already tried this approach with switch and it works without variables.
It's like dax does not allow you to change the value of a variable after the first time it was assigned.
edit
hello, here is the example of what I want to achieve:
Value Daily Form =
SWITCH( true(),
// if both are selected
(ISFILTERED(tblAAA[AAA_name]) && ISFILTERED(tblBBB[BBB_name])),
var Target = sum(F_Daily_AAA_BBB[target])
var TotalPayments = sum(F_Daily_AAA_BBB[vlr_total_payment])
// if AAA is selected
, (ISFILTERED(tblAAA[AAA_name]) && not(ISFILTERED(tblBBB[BBB_name]))),
var Target = sum(F_Daily_AAA[target])
var TotalPayments = sum(F_Daily_AAA[vlr_total_payment])
// if BBB is selected
, (not(ISFILTERED(tblAAA[AAA_name])) && ISFILTERED(tblBBB[BBB_name])),
var Target = sum(F_Daily_BBB[target])
var TotalPayments = sum(F_Daily_BBB[vlr_total_payment])
// none is selected
,
var Target = sum(F_Daily_OR[target])
var TotalPayments = sum(F_Daily_OR[vlr_total_payment])
)
var result =
SWITCH(FIRSTNONBLANK(tblKPIs[Group_Name], tblKPIs[Group_Name]),
"Target (€)", IF(Target > 0, FORMAT(Target, "€ #,##"), if(SELECTEDVALUE('Calendar'[isWorkingDay]) = 1, "€ 0", BLANK())),
"Total Payments (€)", IF(TotalPayments > 0, FORMAT(TotalPayments, "€ #,##"), IF(SELECTEDVALUE('Calendar'[isWorkingDay]) = 1, "€ 0", BLANK())),
)
return result
in the beginning the code that I have to modify is:
Value Daily Form =
var Target = sum(F_Daily_OR[target])
var TotalPayments = sum(F_Daily_OR[vlr_total_payment])
var result =
SWITCH(FIRSTNONBLANK(tblKPIs[Group_Name], tblKPIs[Group_Name]),
"Target (€)", IF(Target > 0, FORMAT(Target, "€ #,##"), if(SELECTEDVALUE('Calendar'[isWorkingDay]) = 1, "€ 0", BLANK())),
"Total Payments (€)", IF(TotalPayments > 0, FORMAT(TotalPayments, "€ #,##"), IF(SELECTEDVALUE('Calendar'[isWorkingDay]) = 1, "€ 0", BLANK())),
)
return result
The only difference is the instead of 2 variables there are like 75,
and I don't want to make a switch for each of them because this will spaghettify the code.
Also I have to modify like 50 of this Metrics full of variables, so I need a quick copy paste solution like that switch, which worked in other cases in which the code didn't have variables.
Thank you for taking the time to help me.
It is indeed, because variables in DAX are actually constants. Variables are immutable. You can store the value in variable but you cannot change it later.
Here is a definition of the DAX variable from the documentation:
Stores the result of an expression as a named variable, which can then be passed as an argument to other measure expressions. Once resultant values have been calculated for a variable expression, those values do not change, even if the variable is referenced in another expression.
Find more in the documentation.
What exactly do you want to achieve by this?
Creating separate measure for each condition and then another measure with switch condition won't work for you?
Related
Is there a way of placing three different types of variables into a one column using switch? Or is there a better way of doing it? Or can it be done?
So I have one set of parameters that work in the switch but a few tricky ones that dont work. Here is what I have so far.
Var a = switch ([customer],
"Customer 1001" , "USA",
"Customer 1002", "Asia", "Other ...... and so on
Var b = if [Customer] = "Customer 2002" && [cat] <> "Household" THEN " USA" else "Europe"
Var c = if [Customer] = "Customer 2002" && [order date] > "2021/10/01" then "USA" else "Asia"
You can declare multiple variables within an expression, Measure/Calculated Column/Calculated Table. Just keep in mind they will only be evaluated if refered to, lazy evaluation, and once assigned within it's scope they can't be overwritten.
Example:
My Calculation =
var a = 1
var b = 2
RETURN
a+b
Your problem might be with the incorrect use of the IF.
https://learn.microsoft.com/pt-pt/dax/if-function-dax
Example:
My Calculation =
var a = "Customer 1001"
RETURN
IF(a = "Customer 1001", "USA" , "Other")
I have a table that is something like this:
ID
A
B
1H4
6S8
True
1L7
True
6T8
True
7Y8
6S2
True
True
1H1
True
6S3
True
1H9
True
True
6S0
I want to create a measure that evaluates a table to be able to conditionally (to later make conditional rules for report i.e. place color values in such cells) evaluate the cells for the following 2 conditions:
when there are values in both Column A and Column B
when there are blanks/nulls in both columns
(If both can be done in a single measure this would be ideal)
You can use a measure like this:
Background Color =
var Count_A = COUNTBLANK('Table'[A])
var Count_B = COUNTBLANK('Table'[B])
RETURN
SWITCH(TRUE();
AND(Count_A = 0; Count_B = 0); "Red";
AND(Count_A > 0; Count_B > 0); "Green";
"")
First count the blank values in each of the columns, and then return a different color, depending on both counts. Then use this measure to conditionally format the background color for each of the columns:
to get something like this:
You'll need a custom column with the logic of
Column name =
SWITCH (
TRUE (),
A = 'True'
&& B = 'True', "True",
A = ''
&& B = '', "False",
"Else goes here"
)
You'll have to change the logic if the cells without anything in them are '' or true blanks. SWITCH acts like a multiple IF statement, and Switch with TRUE() evaluates the conditions in the later steps.
You can achieve the desired result by using both custom columns and measures.
Custom Column
Column =
IF (
Table[A] <> BLANK ()
&& Table[B] <> BLANK (),
"Green",
IF ( Table[A] = BLANK () && Table[B] = BLANK (), "Red" )
)
Measure
Measure X =
IF(COUNTBLANK(Table[A]) = 0
&& COUNTBLANK(Table[B]) = 0 , "#00FF00",
IF(COUNTBLANK(Table[A]) <> 0
&& COUNTBLANK(Table[B]) <> 0 , "#FF0000")
)
After creating a measure or custom column go to conditional formatting and select background colour, and you may select either measure or column as per your choice. this will give you the desired result.
Output
I have a following data table:
I need to create a column called FINAL VALUE with certain rules in the power query editor:
The FINAL VALUE is created based on the COUNTRY
If VALUE is greater than 100, then the previous value will be taken
if the previous values (no previous value such as 202001) are all greater than 100, then 100
So the final table should look like:
I sort COUNTRY and DATE, and then I try to apply loop in M Query. As I am not familiar with the function in M query, I have hard time figuring out. I appreciate any help. Thank you.
I believe you are better of in DAX. You can create a new column like below:
Final Value =
var curCountry = TableCountry[Country]
var curDate = TableCountry[Date]
var prevDate = CALCULATE(MAX(TableCountry[Date]), FILTER(TableCountry, curDate >= TableCountry[Date] && curCountry = TableCountry[Country] && TableCountry[Value] <=100))
return LOOKUPVALUE(TableCountry[Value], TableCountry[Country], curCountry, TableCountry[Date], prevDate, 100)
I am wondering if something that i would like to achieve is possible, please look at the picture and read description below:
I would like to add a column to the right, where if a cell table[ActionType] = "TERMINATING", it calculates a difference between timestamps (timestamp for TERMINATING - timestamp for STARTING in below row). If the result is positive (>0) then store it in a column in a corresponding row (eg next to timestapm for terminating), if result is negative don't store it. And all of that applied to whole table.
I tried conditional column and i guess it cannot be done with this or at least I couldn't make it.
Will be very thankful for responses and tips!
Pre-requisite :- Add an Index Column using the query editor. Make sure they are in the next row to each other.
It is advisable to keep TimeStamp column as a DateTime Column itself.
So, if you can change your TimeStamp column to a DateTime column then try this :-
Difference =
Var Get_Action_Type = Table1[ActionType]
Var required_Index_1 = Table1[Index] + 1
Var required_Index = IF(required_Index_1 > MAX(Table1[Index]),required_Index_1-1, required_Index_1)
Var Current_Action_TimeStamp = Table1[TimeStamp]
Var next_Action_TimeStamp = CALCULATE(MAX(Table1[TimeStamp]),FILTER(Table1, Table1[Index] = required_Index))
Var pre_result = IF(Get_Action_Type = "TERMINATING", DATEDIFF(Current_Action_TimeStamp, next_Action_TimeStamp,SECOND), BLANK())
Var result = IF(pre_result > 0, pre_result, BLANK())
return result
And if you cannot change it to a Date Time, then try this calculated column,
Difference_2 =
Var Get_Action_Type = Table1[ActionType]
Var required_Index_1 = Table1[Index] + 1
Var required_Index = IF(required_Index_1 > MAX(Table1[Index]),required_Index_1-1, required_Index_1)
Var Current_Action_TimeStamp = Table1[Time_Stamp_Number]
Var next_Action_TimeStamp = CALCULATE(MAX(Table1[Time_Stamp_Number]),FILTER(Table1, Table1[Index] = required_Index))
Var pre_result = IF(Get_Action_Type = "TERMINATING", next_Action_TimeStamp - Current_Action_TimeStamp, BLANK())
Var result = IF(pre_result > 0, pre_result, BLANK())
return result
The Output looks as below :-
Kindly accept the answer if it helps and do let me know, how it works for you.
I need a formula that will help me calculate the $ expense amount for my milage rates.
Here is my sheet https://docs.google.com/spreadsheets/d/1PPFuFWbxWi9iIdtYBJvnSNB1j1cjjQutepF3hnpGoFM/edit?usp=sharing
On the tab that's expenses, I need to check the year of my date in Col A (because different years have different rates), then check Col D to see if it says Milage, then check Col E for what type of milage (there are 4 types), then return the number input in Col I times the appropriate rate for that year and type of milage. I have a table set up with the rates in another tab.
I'm thinking it will be a long IF and AND formula. Any help would be great!
In 'Essentials Log', I've changed the format of your year start-end dates to state the year you're referencing. I've added a column for "Milage".
Expense Reference Screenshot
In 'Expenses'!M2, I tried this and it seems to work:
=ARRAYFORMULA(iferror(if(isblank(A2:A),"",I2:I*vlookup(D2:D&year(A2:A)&E2:E,query({'Essentials Log'!Y2:Y&'Essentials Log'!Z2:Z&'Essentials Log'!AA2:AA,'Essentials Log'!AB2:AB},"Select *"),2,false))))
Working Example Screenshot
Have a look (I copied your example sheet): Milage expense
I solved this with creating an app script.
I realized I didn't want to use a formula because in my $ col most entries will be keyed in and so I didn't want to copy and paste a formula every time.
Here is the code if anyone might need it. I added it to the menu so the calculation is done with a click.
function expenseMilageCalculation() {
var auditionsSheet = SpreadsheetApp.getActiveSpreadsheet();
var expensesTab = auditionsSheet.getActiveSheet();
var activeCell = expensesTab.getActiveCell();
var activeRow = activeCell.getRow();
var expenseDate = expensesTab.getRange(activeRow, 1).getValue();
var expenseYear = expenseDate.getFullYear();
var expenseType = expensesTab.getRange(activeRow, 4).getValue();
var expenseDetails = expensesTab.getRange(activeRow, 5).getValue();
var numMiles = expensesTab.getRange(activeRow, 9).getValue();
var essentialsLogTab = auditionsSheet.getSheetByName("Essentials Log")
//2018 Business Milage
if (expenseYear == 2018 && expenseType == "Milage" && expenseDetails == "Business") {
var milageBusinessRate2018 = essentialsLogTab.getRange(3, 27).getValue();
var dollarMilesDeduction = numMiles * milageBusinessRate2018
expensesTab.getRange(activeRow, 8).setValue(dollarMilesDeduction)
}
//2019 Business Milage
if (expenseYear == 2019 && expenseType == "Milage" && expenseDetails == "Business") {
var milageBusinessRate2019 = essentialsLogTab.getRange(8, 27).getValue();
var dollarMilesDeduction = numMiles * milageBusinessRate2019
expensesTab.getRange(activeRow, 8).setValue(dollarMilesDeduction)
}