Forum Discussion

mp390988's avatar
mp390988
Icon for Post Partisan rankPost Partisan
1 year ago
Solved

Filter vs Calculatetable - different behaviour resulting in different answers

Hi, I have the following DAX formula inside a calculated column: Code: WorkingDays = var lastDateOfMonth = ENDOFMONTH(dimDate[Date]) var startDate = date(dimDate[Year], dimDate[MonthNum],...
  • johnt75's avatar
    1 year ago

    This is rather intricate. Your syntax for the version using FILTER is incorrect. The columns you reference in the filter conditions must be included in the table you are trying to filter, and in this case dimDate[IsHoliday] is not included in the table generated by DISTINCT(dimDate[date]). Indeed, if you run

    EVALUATE
    FILTER ( DISTINCT ( dimDate[date] ), dimDate[IsHoliday] = 1 )
    

    in DAX Query View you will get an error saying that a single value for IsHoliday cannot be determined.

    The reason you don't get an error when running it in the calculated column is because a single value can be determined - in a calculated column you have a row context, which means the filter condition is checking the value of IsHoliday in the current row, not in the table you are trying to filter.

    The reason that the version with CALCULATETABLE almost works is because you can specify a column which is not included in the base table. However, because you are retrieving values from the table in which you have a row context, because you are in a calculated column, you need to remove the existing filters generated by the row context.

    Finally, you don't need to generate a variable for end date, you can just use the last day of the month. The final code should be

    WorkingDays =
    VAR lastDateOfMonth =
        EOMONTH ( dimDate[Date], 0 )
    VAR startDate =
        DATE ( dimDate[Year], dimDate[MonthNum], 1 )
    VAR holidays =
        CALCULATETABLE (
            DISTINCT ( dimDate[date] ),
            dimDate[IsHoliday] = 1,
            REMOVEFILTERS ( dimDate )
        )
    RETURN
        NETWORKDAYS ( startDate, lastDateOfMonth, 1, holidays )
    
  • v-csrikanth's avatar
    1 year ago

    Hi mp390988 
    No, REMOVEFILTERS(dimDate) clears existing filters from the dimDate table before applying new filters inside CALCULATETABLE.
    The condition dimDate[IsHoliday] = 1 is still active and reapplied after the REMOVEFILTERS step inside CALCULATETABLE's logic.
    Thus, the final result will correctly include only dates where IsHoliday = 1, not all dates.

    Best Regards,
    Cheri Srikanth