Forum Discussion

BryonScruggs's avatar
BryonScruggs
Frequent Visitor
3 years ago
Solved

DAX Variable Scope - Cannot create variables within the correct row context

Hello Internet,    I am working on a problem involving the scope of DAX variables. My code defines the hire date and termination date of employees and them implements logic based on the result. My ...
  • v-jialluo-msft's avatar
    3 years ago

    Hi BryonScruggs ,

     

    Please follow these steps:

    (1) Create a new Table

    Employment Cases = 
    VAR PeriodStart =
        DATE ( 2022, 01, 01 )
    VAR PeriodEnd =
        DATE ( 2022, 03, 31 )
    
    RETURN
        ADDCOLUMNS (
            SELECTCOLUMNS (
                attr_Tkpr_vw,
                "EmpID", attr_Tkpr_vw[TkprNumber],
                "Hire", attr_Tkpr_vw[TkprDateHire],
                "Term", attr_Tkpr_vw[TkprDateTerm],
                "Hire Test",
                    CALCULATE (
                        MIN ( attr_Tkpr_vw[TkprDateHire] ),
                        ALLEXCEPT ( attr_Tkpr_vw, 'attr_Tkpr_vw'[TkprNumber] )
                    ),
                "Term Test",
                    CALCULATE (
                        MIN ( attr_Tkpr_vw[TkprDateTerm] ),
                        ALLEXCEPT ( attr_Tkpr_vw, 'attr_Tkpr_vw'[TkprNumber] )
                    )
            ),
            "Employment Period",
                SWITCH (
                    TRUE (),
                    AND ( AND ( [Hire] >= PeriodStart, [Hire] <= PeriodEnd ), [Term] >= PeriodEnd ), DATEDIFF ( [Hire Test], PeriodEnd, MONTH ),
                    AND (
                        AND ( [Hire] >= PeriodStart, [Hire] <= PeriodEnd ),
                        AND ( [Term] >= PeriodStart, [Term] <= PeriodEnd )
                    ), DATEDIFF ( [Hire Test], [Term Test], MONTH )
                )
        )

     

    (2)Final output

     

     

    If that's not what you need, please share the sample file

     

    Best Regards,

    Gallen Luo

    If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.