Forum Discussion

uadrian92's avatar
uadrian92
Frequent Visitor
4 years ago
Solved

CALCULATE and FILTER behavior

Hey,

 

I'm trying to wrap my head around the following:

 

I have 2 simple tables:

 

 

The contents of these 2 tables:

Orders:

order_idproductstatus_id
1Bike1
2Bike1
3Skateboard2
4Skateboard3
5Laptop2

 

status:

status_idstatus
1Delivered
2Refunded
3Payment Error

 

I have 3 measures:

 

Count = COUNTROWS('Orders')
Count Refunded = 
CALCULATE(
    [Count],
    'status'[status] = "Refunded")
Count Refunded with Filter = 
CALCULATE(
    [Count],
    FILTER(
        'status',
        'status'[status] = "Refunded"))

 

 

And they produce these results:

(The 3 matrices have the same row/column fields: Orders[product] and status[status]).

 

I understand why I get the results with Count Refunded: Calculate overrides the context, so no matter what I have in columns, it will always be the count of refunded items (Bonus question though: why do "Delivered" and "Payment Error" get the same values as "Refunded"? Shouldn't they just be 0 [or blank]?). In this case, columns stay.

 

However, when I do kinda the same but with FILTER in CALCULATE, the rest of the columns (Delivered, Payment Error) disappear.

 

So the question is: what causes this behavior? (I'm probably missing something with the FILTER function but I'm not sure what)

 

Sample file: calculate and filter.pbix 

 

3 Replies

    • uadrian92's avatar
      uadrian92
      Frequent Visitor

      Although this article alone didn't give me the "aha moment" yet (especially the last case, where columns "disappear" when using FILTER), but gave me a good starting point on where I should be digging further 🙂

       

      I probably just need to sit down and go through the process step by step to have a better understanding on how DAX/FILTER/CALCULATE really work behind the scenes 🙂

       

      Thanks!

      • DataInsights's avatar
        DataInsights
        Icon for Super User rankSuper User

        uadrian92,

         

        In the second visual (Count Refunded), the columns Delivered and Payment Error have the value 1 because CALCULATE overrides the filter context of status[status], and returns the value for Refunded. If you want to exclude Delivered and Payment Error, you can use KEEPFILTERS:

         

        Count Refunded = 
        CALCULATE(
            [Count],
            KEEPFILTERS ( 'status'[status] = "Refunded") )

         

        This will keep the filter for Delivered and Payment Error resulting in blank (a row can't have a status of both Delivered and Refunded). The result is the same as the third visual:

         

         

        Keep in mind that a column filter and table filter will return the same result in certain scenarios, but not all scenarios. Thus, it's best to follow the aforementioned golden rule. 🙂