Aller au contenu

DAX: what is the difference between CALCULATE with and without FILTER?

par Équipe NextData

0

In DAX I can write a condition directly as an argument of CALCULATE, or wrap it in FILTER. Both often return the same number. When do they differ, and which should I use?

Signaler

1 réponse

0

A condition written directly in CALCULATE is a shortcut. These two measures are equivalent:

Red Sales = CALCULATE ( [Sales], Product[Color] = "Red" )

Red Sales = CALCULATE ( [Sales], FILTER ( ALL ( Product[Color] ), Product[Color] = "Red" ) )

The key is ALL ( Product[Color] ): the shortcut replaces any existing filter on that column. If a slicer selects "Blue", Red Sales still returns red sales.

The behaviour changes when FILTER iterates the whole table in the current context:

Red Sales 2 = CALCULATE ( [Sales], FILTER ( Product, Product[Color] = "Red" ) )

Here FILTER ( Product, ... ) only sees the products still visible. With "Blue" selected, no row passes and the measure returns blank.

Which to use:

  • Simple condition on one column: the direct form. It is shorter.
  • Keep the user's selection instead of replacing it: wrap the condition in KEEPFILTERS.
Red Sales Kept = CALCULATE ( [Sales], KEEPFILTERS ( Product[Color] = "Red" ) )
  • Condition that compares against a measure: FILTER over the values of a column, not over the table.
Big Customers = CALCULATE ( [Sales], FILTER ( VALUES ( Customer[Id] ), [Sales] > 10000 ) )

For the reviewer to check: recent DAX versions accept conditions on several columns of the same table in the direct form. None of the four measures has been executed: create them in a real model and compare the results with a slicer set to another colour.

Réponse rédigée par l'équipe NextData et relue par un expert.

Équipe NextData

Signaler

Votre réponse

Connectez-vous pour répondre