powerbidax

Filtering for all records where date is less than slicer value in Power BI


I have a table named Scheme in Power BI that looks like the following:

SchemeName SchemeYear
Scheme A 2008-01-01
Scheme B 2009-01-01
Scheme C 2010-01-01
Scheme D 2011-01-01
Scheme E 2011-01-01
Scheme F 2012-01-01

What I am trying to do is create logic so that when I add Scheme to a slicer, I can filter a visual to return all schemes equal to or prior to the selected scheme. For example, if Scheme C is selected from the slicer, Schemes A - C should be displayed. If Scheme D is selected, Schemes A - E are displayed. If Scheme F is selected, all Schemes are displayed.

I've created a disconnected (no relationship) table named SchemeSlicer for use in the slicer and I have the following logic for a custom measure in the Scheme table:

ShowSchemes = 
VAR SelectedScheme = SELECTEDVALUE(SchemeSlicer[SchemeName])
VAR SelectedYear =
    CALCULATE(
        MAX('Scheme'[SchemeYear]),
        'Scheme'[SchemeName] = SelectedScheme
    )
RETURN
IF(MAX('Scheme'[SchemeYear]) <= SelectedYear, 1, 0)

I then apply this measure as a filter to a visual and set it to 'Show items when the value is 1':

A screen capture of a filter in Power BI. It is set to filter for items in the ShowScheme measure where the value is 1.

However, this only returns schemes in the same year, e.g. only Scheme D and E are returned if I select either of them with my slicer.

I think this is a problem with the row-wise evaluation, but I'm not used to how data is modelled in Power BI and I'm not sure how to fix it.


Solution

  • You will need to remove the row context for VAR SelectedYear otherwise it will only get the selected year of that row. You can do that via ALL, ALLSELECTED, or REMOVEFILTERS. For example:

    VAR SelectedYear =
      CALCULATE(
        MAX('Scheme'[SchemeYear]),
        'Scheme'[SchemeName] = SelectedScheme,
        REMOVEFILTERS(Scheme)
      )
    

    Supplemental: Suggest updating VAR SelectedScheme to:

    VAR SelectedScheme = MAX(SchemeSlicer[SchemeName])
    

    With MAX you will always get a value, eg if slicer has no selection or slicer has multiple values selected, whereas SELECTEDVALUE will return null in both of these scenarios.