Detailed Guide to SWITCH function in DAX

by | Power BI

Introduction to the SWITCH Function in DAX

The SWITCH function in DAX is a powerful and flexible tool useful for performing multiple conditional tests and outcomes within your data models. This guide will walk you through the basics of the SWITCH function, including its syntax and practical examples to help you apply it in your Power BI reports.

Syntax

The basic syntax of the SWITCH function is as follows:

SWITCH( <Expression>, <Value1>, <Result1> [, <Value2>, <Result2>]…[, <Else>] )
  • Expression: This is the value or expression that you want to evaluate.
  • Value1, Value2, …: These are the specific values that the expression is compared against.
  • Result1, Result2, …: These are the outcomes or results returned when the corresponding values match the expression.
  • Else (optional): The default result if none of the specified values match the expression.

Practical Examples

1. Basic Usage

Imagine you have a table of students with an “ExamScore” column and you want to categorize their performance.

PerformanceCategory = 
SWITCH(
    TRUE(), 
    Students[ExamScore] >= 90, "Excellent",
    Students[ExamScore] >= 75, "Good",
    Students[ExamScore] >= 50, "Average",
    "Poor"
)

In this example:

  • If the exam score is 90 or above, the student is categorized as “Excellent”.
  • If the score is between 75 and 89, the category is “Good”.
  • If the score is between 50 and 74, the category is “Average”.
  • Any other score (less than 50) results in a “Poor” category.

2. Detailed Evaluation

Suppose you have sales data, and you want to assign a “Discount Category” based on the “SalesAmount”.

DiscountCategory = 
SWITCH(
    TRUE(),
    Sales[SalesAmount] > 1000, "High",
    Sales[SalesAmount] > 500, "Medium",
    Sales[SalesAmount] > 100, "Low",
    "None"
)
  • For sales amounts greater than 1000, the discount category is “High”.
  • For amounts between 501 and 1000, the category is “Medium”.
  • For amounts between 101 and 500, the category is “Low”.
  • For amounts 100 or less, no discount is applied.

3. Advanced Evaluations

Imagine a scenario where you need to classify products based on both sales amount and profit margin.

ProductClassification = 
SWITCH(
    TRUE(),
    AND(Sales[SalesAmount] > 1000, Sales[ProfitMargin] > 20), "Premium",
    AND(Sales[SalesAmount] > 500, Sales[ProfitMargin] > 15), "Standard",
    Sales[SalesAmount] > 100, "Budget",
    "Economy"
)
  • Products with sales amount over 1000 and profit margin over 20% are classified as “Premium”.
  • Sales over 500 and profit margin over 15% are classified as “Standard”.
  • Sales over 100 are classified as “Budget”.
  • Anything else falls into the “Economy” category.

Conclusion

The SWITCH function in DAX is an essential tool for categorizing and transforming your data based on various conditions. Using the examples provided, you can start integrating complex conditional logic into your Power BI reports to enhance your data analysis capabilities. Make sure to apply these techniques directly in your Power BI environment to see how they can transform your data insights.

Practical Examples of the SWITCH Function

Example 1: Categorizing Sales Performance

To categorize the sales performance based on total sales, you can use the SWITCH function in this format:

Sales Performance = SWITCH(
    TRUE(),
    [Total Sales] < 5000, "Low",
    [Total Sales] >= 5000 && [Total Sales] < 15000, "Medium",
    [Total Sales] >= 15000, "High",
    "Undefined"
)

In this example:

  • If [Total Sales] is less than 5000, the result will be “Low”.
  • If [Total Sales] is between 5000 and 15000, the result will be “Medium”.
  • If [Total Sales] is 15000 or more, the result will be “High”.
  • If none of the conditions are met, it will return “Undefined”.

Example 2: Mapping Region Codes to Region Names

If you have region codes in your dataset and want to map them to human-readable region names, the SWITCH function can be utilized as follows:

Region Name = SWITCH(
    [Region Code],
    1, "North America",
    2, "Europe",
    3, "Asia",
    4, "South America",
    5, "Africa",
    6, "Australia",
    "Other"
)

Here:

  • If [Region Code] is 1, it will return “North America”.
  • If [Region Code] is 2, it will return “Europe”.
  • If [Region Code] is 3, it will return “Asia”.
  • If [Region Code] is 4, it will return “South America”.
  • If [Region Code] is 5, it will return “Africa”.
  • If [Region Code] is 6, it will return “Australia”.
  • If [Region Code] does not match any of the specified values, it will return “Other”.

Example 3: Conditional Formatting Based on Score Ranges

To dynamically categorize and format student scores:

Score Category = SWITCH(
    TRUE(),
    [Score] >= 90, "Excellent",
    [Score] >= 75 && [Score] < 90, "Good",
    [Score] >= 50 && [Score] < 75, "Average",
    [Score] < 50, "Poor",
    "Undefined"
)

This expression works in the following way:

  • If [Score] is 90 or more, the result is “Excellent”.
  • If [Score] is between 75 and 90 (exclusive), the result is “Good”.
  • If [Score] is between 50 and 75 (exclusive), the result is “Average”.
  • If [Score] is less than 50, the result is “Poor”.
  • If none of these conditions are met, the default result is “Undefined”.

Make sure to use these DAX examples in your Power BI data models to perform dynamic calculations and categorizations efficiently.

Advanced Use Cases of SWITCH in DAX

This section explores advanced scenarios where the SWITCH function in DAX can be utilized effectively. We will cover nesting, integrating with other functions, and handling complex business rules.

Nested SWITCH Statements

Sometimes business logic requires multiple layers of conditions. Here’s how you can handle nested SWITCH statements.

Category =
SWITCH(
    TRUE(),
    [Value] < 10, "Low",
    [Value] >= 10 && [Value] < 20,
    SWITCH(
        TRUE(),
        [SubValue] < 5, "Medium-Low",
        [SubValue] >= 5, "Medium-High",
        "Medium"
    ),
    "High"
)

Using SWITCH with CALCULATE for Context Modification

You can modify the context of a calculation by combining SWITCH with CALCULATE.

RegionSales =
SWITCH(
// Check the region
    [Region],
    "North",
        CALCULATE(SUM(Sales[Amount]), Sales[Region] = "North"),
    "South",
        CALCULATE(SUM(Sales[Amount]), Sales[Region] = "South"),
    "Others",
        CALCULATE(SUM(Sales[Amount]), NOT(Sales[Region] IN {"North", "South"}))
)

Combining SWITCH with AND/OR Conditions

For more complex logical conditions, you can combine SWITCH with AND/OR.

EmployeeStatus = 
SWITCH(
    TRUE(),
    AND(Employee[YearsOfService] > 5, Employee[PerformanceRating] >= 4), "Eligible for Promotion",
    OR(Employee[YearsOfService] > 3, Employee[PerformanceRating] >= 3), "Under Consideration",
    "Not Eligible"
)

Advanced EVALUATION Combinations

Integrate SWITCH with other evaluation functions like LOOKUPVALUE, RELATED, and RELATEDTABLE.

ProductCategory =
SWITCH(
    TRUE(),
    [ProductID] = LOOKUPVALUE(Products[ProductID], Products[ProductName], "Laptop"), "Electronics",
    [ProductID] IN VALUES(Inventory[ProductID]), "In Stock",
    RELATED(Suppliers[SupplierName]) = "Best Supplier", "Preferred Supplier",
    "Miscellaneous"
)

SWITCH with Multiple Measure Conditions

You can also apply SWITCH to select different measures based on conditions.

SelectedMeasure =
SWITCH(
    SELECTEDVALUE(Measures[MeasureName]),
    "Total Sales", [Total Sales],
    "Total Profit", [Total Profit],
    "Total Costs", [Total Costs]
)

By incorporating these advanced use cases, you can extend the power and flexibility of the SWITCH function in DAX to handle complex business logic, ultimately enabling deeper insights and more sophisticated data analysis within Power BI.

Combining SWITCH with Other DAX Functions

To elevate your DAX skills in Power BI, let’s explore how to combine the SWITCH function with other DAX functions like CALCULATE, SUM, IF, and DATE functions.

Example 1: Combining SWITCH with CALCULATE

Total Sales by Category = 
SWITCH(
    TRUE(),
    'Sales'[Category] = "A", CALCULATE(SUM('Sales'[Total Sales]), 'Sales'[Category] = "A"),
    'Sales'[Category] = "B", CALCULATE(SUM('Sales'[Total Sales]), 'Sales'[Category] = "B"),
    'Sales'[Category] = "C", CALCULATE(SUM('Sales'[Total Sales]), 'Sales'[Category] = "C"),
    BLANK()
)

Example 2: Combining SWITCH with IF and Date Functions

Sales Performance = 
VAR CurrentYear = YEAR(TODAY())
VAR LastYear = CurrentYear - 1
VAR CategorySalesCurrentYear = CALCULATE(SUM('Sales'[Total Sales]), YEAR('Sales'[Date]) = CurrentYear)
VAR CategorySalesLastYear = CALCULATE(SUM('Sales'[Total Sales]), YEAR('Sales'[Date]) = LastYear)
RETURN
SWITCH(
    TRUE(),
    CategorySalesCurrentYear > CategorySalesLastYear * 1.1, "High Growth",
    CategorySalesCurrentYear < CategorySalesLastYear * 0.9, "Decline",
    "Stable"
)

Example 3: Combining SWITCH with SUM and Time Intelligence

Yearly Sales Comparison = 
VAR ThisYear = YEAR(TODAY())
VAR LastYear = ThisYear - 1
VAR SalesThisYear = CALCULATE(SUM('Sales'[Total Sales]), 'Sales'[Year] = ThisYear)
VAR SalesLastYear = CALCULATE(SUM('Sales'[Total Sales]), 'Sales'[Year] = LastYear)
RETURN
SWITCH(
    TRUE(),
    SalesThisYear > SalesLastYear, "Increase",
    SalesThisYear = SalesLastYear, "No Change",
    "Decrease"
)

Example 4: Incorporating SWITCH with AVERAGE and Custom Categories

Customer Satisfaction = 
SWITCH(
    TRUE(),
    AVERAGE('Feedback'[Score]) >= 9, "Highly Satisfied",
    AVERAGE('Feedback'[Score]) >= 7, "Satisfied",
    AVERAGE('Feedback'[Score]) >= 5, "Neutral",
    "Dissatisfied"
)

Example 5: Utilizing SWITCH with SUMX for Calculated Columns

Sales Contribution by Product = 
SWITCH(
    TRUE(),
    'Products'[Product Type] = "Electronics", 
    SUMX(FILTER('Sales', 'Sales'[Product ID] = 'Products'[Product ID]), 'Sales'[Total Sales]) * 0.1,
    'Products'[Product Type] = "Furniture", 
    SUMX(FILTER('Sales', 'Sales'[Product ID] = 'Products'[Product ID]), 'Sales'[Total Sales]) * 0.2,
    SUMX(FILTER('Sales', 'Sales'[Product ID] = 'Products'[Product ID]), 'Sales'[Total Sales]) * 0.05
)

By combining the SWITCH function with various other DAX functions, you can perform advanced calculations and shape your data according to specific business logic. This level of control allows for more dynamic and insightful reporting in Power BI.

Project-Based Learning and Real-World Applications with DAX

In this section, we will implement a real-world project using DAX functions in Power BI, specifically focusing on creating a dynamic dashboard for a sales dataset. The main components include creating measures for advanced data analysis and implementing a dynamic SWITCH-based segmentation.

Dynamic Segmentation Using SWITCH

Scenario

You are a data analyst at a retail company, and you need to segment the sales performance based on different criteria such as “High”, “Medium”, and “Low” sales categories. You will use DAX to create measures that dynamically categorize sales and display them in a Power BI dashboard.

Steps

  1. Create Sales Categories Measure:


    Sales Category = 
    SWITCH(
    TRUE(),
    [Total Sales] >= 1000000, "High",
    [Total Sales] >= 500000, "Medium",
    "Low"
    )

  2. Create Total Sales Measure:


    Total Sales = 
    SUM('Sales'[Sales Amount])

  3. Build a Measure for Performance Based on Segments:


    Sales Performance = 
    SWITCH(
    'Sales'[Sales Category],
    "High", [Total Sales] * 1.2,
    "Medium", [Total Sales],
    "Low", [Total Sales] * 0.8
    )

  4. Create Dynamic KPIs (Key Performance Indicators):


    KPI Category = 
    SWITCH(
    TRUE(),
    [Sales Performance] >= 1200000, "Excellent",
    [Sales Performance] >= 600000, "Good",
    "Needs Improvement"
    )

Implementation in Power BI

  1. Loading Data: Ensure your dataset is loaded into Power BI Desktop, and measures are created as specified above.
  2. Building the Dashboard:
    • Insert a Card Visual to display Total Sales.
    • Create a Table Visual to list individual sales transactions, including the Sales Category and KPI Category measures.
    • Insert a Bar Chart or Pie Chart to visualize the distribution of Sales Category across the dataset.
    • Insert a Gauge Visual or KPI Visual to highlight the overall performance based on the Sales Performance measure.

Example Dashboard Layout

  • Card Visual: Total Sales
  • Table Visual: Columns – Product Name, Sales Amount, Sales Category, KPI Category
  • Bar Chart: Axis – Sales Category, Values – Total Sales
  • KPI Visual: Sales Performance

By following the steps above, you will have dynamically segmented your sales data and used these segments to create meaningful insights through KPIs and visualizations in Power BI. This approach provides a powerful example of applying DAX functions to real-world data analysis tasks.

Related Posts

Comprehensive Data Analysis using Power BI and DAX

Data Model Discovery Library

An interactive web-based application to explore and understand various data model examples across multiple industries and business functions.