Forum Discussion

iplaygod's avatar
iplaygod
Resolver I
7 years ago
Solved

DAX: Using variables inside iterators such as SUMX

Sorry if this has been answered before I could not find any info on it. I would like to know if it is allowed / possible to use variables inside an iterator.   Basically I would like to grab some ...
  • iplaygod's avatar
    iplaygod
    7 years ago

    Thanks for pointing me in the right direction :)

    It turns out you CAN put variables inside iterators, you just need to put them after the first argument.

    This is great because it can greatly enhance readability
    (if you are wondering what all the semicolons ; are about in the code, its because of language settings, its the same as a comma , in us versions)

    So like this:

    SUMX( tableName;
                -- put vars here:
                VAR myVariable = tableName[somevalue]
                VAR myOtherVariable = tableName[someothervalue]
                -- after vars, put the RETURN:
                RETURN
                -- then use the variables in making the return calculations:
                myVariable * myOtherVariable
    )

    ---------

    Heres an example from what I was working on:

    SUMXVARS =
    VAR toCurrency = [Selected Currency] -- from slicer
    VAR currencyRatePeriod = [Selected Currency Rate Period] -- from slicer
    RETURN
    SUMX( 'dummy sales data';
           VAR currRowAmount = 'dummy sales data'[amount]
           VAR currRowTransactionCurrency = 'dummy sales data'[transaction currency]
           VAR currRowDate = 'dummy sales data'[date]
           -- depending on user chosen rate period, we change the date to look for
           VAR targetCurrencyDate = SWITCH(currencyRatePeriod;
                                            "daily"; currRowDate;
                                            "monthly"; DATE( YEAR(currRowDate); Month(currRowDate);1);
                                            "yearly"; DATE( YEAR(currRowDate); 1;1))
                                            
           VAR currencyRate = IF('dummy sales data'[transaction currency] = toCurrency;
                        -- from -> to currency is the same, therefore rate is ALWAYS 1
                         1;
                        -- from -> to currency is different, we need to convert
                        -- go find the right exchange rate value:
                              LOOKUPVALUE(currencyModel[rate];                                                                                    currencyModel[from currency code]; currRowTransactionCurrency ;
                                       currencyModel[to currency code]; toCurrency;  
                                       currencyModel[date]; targetCurrencyDate;
                                       currencyModel[rate period]; currencyRatePeriod)
                       )
                RETURN
                currRowAmount * currencyRate          
        )