Forum Discussion

Anonymous's avatar
Anonymous
Not applicable
7 years ago
Solved

DAX optimization & variables with SWITCH statement

If I have a "master" measure that will return a different calculation based on a disconnected slicer, will the variables be calculated only if needed or will they all be calculated before the RETURN ...
  • jdbuchanan71's avatar
    7 years ago

    Hello Anonymous 

    I believe each Variable will calc before it makes it to the switch but what you can do is turn each variable into a measure then just read your filterTimeCalculations[time_calculation] and do the switch.  This also makes it easier to add additional measures to your list and the measures you do write can be used in other parts of the report.

     

    prior_year = 
        CALCULATE (
            [Total_Labor_Dollars],
            FILTER (
                ALLEXCEPT (
                    dimSalesDates,
                    dimSalesDates[Sales_Week_Number],
                    dimSalesDates[Period_Number]
                ),
                dimSalesDates[Year]
                    = MAX ( dimSalesDates[Year] ) - 1
            )
        )
    prior_year_growth = [Total_Labor_Dollars] - [prior_year]
    prior_year_growth_percent = 
        FORMAT ( DIVIDE ( [prior_year_growth], [prior_year] ), "Percent" )
    prior_year_to_date = 
    VAR filter_week =
        MAX ( dimSalesDates[Week_End_Date] )
    RETURN
        CALCULATE (
            [Total_Labor_Dollars],
            ALL ( dimSalesDates ),
            dimSalesDates[Week_End_Date] <= filter_week - 364)
    year_to_date = 
    VAR filter_week =
        MAX ( dimSalesDates[Week_End_Date] )
    RETURN
        CALCULATE (
            [Total_Labor_Dollars],
            ALLEXCEPT ( dimSalesDates, dimSalesDates[Year] ),
            dimSalesDates[Week_End_Date] <= filter_week
        )
    ytd_growth = [year_to_date] - [prior_year_to_date]
    ytd_growth_percent = 
        FORMAT ( DIVIDE ( [ytd_growth], [prior_year_to_date] ), "Percent" )
    Time_Calculation_Total_Labor_Dollars_2 = 
    VAR TimeCalcSelection = 
        SELECTEDVALUE( filterTimeCalculations[time_calculation], "Current Year")
    
    RETURN
        SWITCH (
            TRUE(),
            TimeCalcSelection = "Current Year", [Total_Labor_Dollars],
            TimeCalcSelection = "Prior Year", [prior_year],
            TimeCalcSelection = "Prior Year Growth", [prior_year_growth],
            TimeCalcSelection = "Prior Year Growth Percent", [prior_year_growth_percent],
            TimeCalcSelection = "Prior Year YTD", [prior_year_to_date],
            TimeCalcSelection = "Current YTD", [year_to_date],
            TimeCalcSelection = "YTD Growth", [ytd_growth],
            TimeCalcSelection = "YTD Growth %", [ytd_growth_percent],
            [Total_Labor_Dollars]
        )