Forum Discussion

TutanRamon's avatar
TutanRamon
Frequent Visitor
1 year ago
Solved

Helper function for date comparison

I have many formulas which calculate a measure. For instace: sales, itemQty, returns, returnQty etc. etc. Basiscally, they all follow the same pattern. For instance:   itemSales = SUM(ob_sales[pai...
  • OwenAuger's avatar
    1 year ago

    Hi TutanRamon 

    I would recommend using a calculation group for this instead. It's not possible to have a "measure" return a table expression then use that as a filter argument within CALCULATE.

     

    You can create a calculation group containing a "Last Year Dynamic" calculation item that handles the two variations of "last year".

    Here is the Microsoft guide on creating calculation groups. You can use either Power BI Desktop or Tabular Editor to create them.

     

    I have attached an example PBIX containing one of my own models.

     

    Your "Last Year Dynamic" calculation item should have an expression similar to this:

     

    VAR SelectedDatesCount = COUNTROWS ( 'calendar' )
    VAR IsSmallSelection = SelectedDatesCount <= 27
    VAR Result =
        IF (
            IsSmallSelection,
            CALCULATE (
                SELECTEDMEASURE ( ),
                DATEADD ( 'calendar'[Date], -52 * 7, DAY )
            ),
            CALCULATE (
                SELECTEDMEASURE ( ),
                SAMEPERIODLASTYEAR ( 'calendar'[Date] )
            )
        )
    RETURN
        Result

     

    SELECTEDMEASURE() is a placeholder for any measure that the calculation item is applied to. Calculation items can only be applied to measures, not general expressions.

     

    Once you've created a calculation group and calculation item, you can apply the calculation item to measures by either:

    1. Applying the calculation item as a filter in the report page.
    2. Applying the calculation item as a filter within a DAX expression.

    Here is a report page showing both methods.

    • "Last year" relative to 1-Feb-2021 is 3-Feb-2020
    • "Last year" relative to Feb-2021 is Feb-2020

    The measure Sales Amount Last Year Dynamic applies the "Last Year Dynamic" calculation item as follows:

    CALCULATE (
        [Sales Amount],
        'Time Intelligence'[Time Calc] = "Last Year Dynamic"
    )

    There is an alternative method where you can create table functions using DETAILROWS, but I wouldn't recommend it as it's not intended for this purpose. But you can read up on it here.

     

    Regards