The Switch() Function in Microsoft Power BI
- timothyjwhite20
- Jul 27, 2022
- 2 min read
For those new to programming, an IF-THEN statement is a function that executes a specific code segment if when a certain condition is met. It is formally known as a logical operator. In C, Python and many other programming languages, multiple scenarios can be executed in one block through an IF-ELSE-ELSE... scenario.
Power BI can utilize an IF statement easily through a trigger, a statement/value to execute if true, and a statement/value to execute if false. However, an IF-ELSE loop can become a bit or quite a bit complicated depending on the level of complexity required. It becomes a what's referred to as a nested IF statement, and IF(expression, TRUE, IF( expression, TRUE, FALSE)). In my experience, the more I type, the more I tend to overlook things like parenthesis and other syntax.
Enter the SWITCH() function. It allows the user to create the equivalent of a nested IF statement without the associated headache. As a for instance, if the user wanted to associate a month name from a column that only had month numbers, the switch function could do this easily. The syntax would be as follows
= SWITCH([Month], 1, "January", 2, "February", 3, "March", 4, "April" , 5, "May", 6, "June", 7, "July", 8, "August" , 9, "September", 10, "October", 11, "November", 12, "December" , "Unknown month number" )
The description on the Microsoft FAW describes the function as
SWITCH(<expression>, <value>, <result>[, <value>, <result>]…[, <else>])
While lacking the functionality of a traditional IF statement, it is still a very useful tool for created a calculated column or measure.
For more information on this function and many others, visit the Microsoft FAQ website. Feel free to send and email or post a comment if the FAQ gets a bit confusing.
Comentários