CALCULATE in Power BI: What it is, syntax, and practical examples

CALCULATE is perhaps the most important and popular function within Power BI. That's because it's simple to apply. Convenient and versatile, thanks to this function you can expand the scope of data analysis and create even more interesting reports. For this reason, in the following article, we will let you discover what the Power BI CALCULATE function is, how to use it and what its syntax is. Of course, practical examples cannot be missing.

What you'll find in this article

  • Introducing DAX in Power BI
  • What are DAX functions in Power BI
  • What is the CALCULATE function in Power BI?
  • CALCULATE by Power BI: syntax
  • How to use CALCULATE in Power BI?
  • CALCULATE by Power BI: practical examples
CALCULATE in Power BI: What it is, syntax, and practical examples

Introducing DAX in Power BI

Data Analysis Expressions (DAX) represent advanced formulas for analyzing and calculating data. In Power BI, DAX is the engine that manages all calculations, offering a flexible and powerful set of tools. Thanks to DAX, you can generate new fields and tables directly in the data model.

Power BI, together with other business intelligence tools, effectively uses the available data thanks above all to the power of the DAX formulas integrated into Power BI.

What does it mean that DAX is a functional language? It means that each piece of code acts like a function. This means that it is possible to include conditional statements, nested functions, references to values, and other components, all of which can be used within a DAX expression for execution.

DAX formulas can handle two main types of data: numeric and non-numeric. The interpretation of DAX expressions takes place starting from the innermost function and then proceeding outwards. For this reason, it's essential to structure a DAX formula in a clear and organized way.

Although DAX is closely tied to Power BI, it is also used in Power Pivot for Excel and in SQL Server analysis services (SSAS).

Is it possible to perform calculations in Power BI?

Obviously it is possible to do calculations in Power BI, thanks to DAX formulas. These DAX formulas look like Excel formulas, sharing many of the same functions. However, unlike Excel, DAX functions are designed to operate on data that is interactively dissected or filtered within a report, such as those in Power BI Desktop.

In Excel, each row in a table can have a unique formula. However, in Power BI, a DAX formula created for a new column generates a result for each row in the table. The values in these columns are automatically updated whenever the underlying data is updated or changed.

When a business problem requires complex or customized calculations that go beyond simple SUM or AVERAGE functions, it is essential to create DAX formulas. Although a basic understanding of the Power BI interface allows you to efficiently create and share online reports, understanding the use of DAX functions in Power BI is essential for performing more complex calculations and for conducting advanced dimensional analysis.

What are DAX functions in Power BI

The DAX language, Data Analysis Expressions, is nothing more than a set of functions and operators through which it is possible to create formulas for expressions in Power BI Desktop, but also in Excel Power Pivot and in Microsft SQL Server Analysis Services.

DAX includes a library of about 200 functions, operators and constructs, through which it is possible to create various formulas to calculate results for any kind of problem or need for data analysis. This aims to create a great deal of flexibility in the DAX language.

A DAX function is essentially a predefined formula designed to perform specific calculations using the arguments provided. These arguments must follow a precise sequence and can include various types of inputs such as column references, numeric values, text, constants, other formulas or functions, or logical values such as TRUE or FALSE.

Each DAX function is designed to perform a specific operation on the values provided as arguments. In a DAX formula, you have the flexibility to include multiple topics, thus allowing for a range of complex calculations and analyses.

Let's look at some of the Power BI DAX features:

  • The time intelligence functions in DAX are designed to take advantage of intrinsic calendar and date information, facilitating advanced calculations. By integrating time intervals and dates with aggregations or other processing, these functions allow detailed comparisons between sales, inventory, and other metrics over equivalent time intervals.
  • Date and time functions are used to perform calculations involving date and time values.
  • Logical functions are designed to evaluate expressions or arguments, returning TRUE or FALSE based on the satisfaction of the specified condition. On the other hand, mathematical and trigonometric functions are used to perform a series of mathematical operations on the values provided.

DAX formulas are essential in Power BI for performing calculations both in calculated columns and in measures. In addition, DAX is crucial for enforcing row-level security measures, thus ensuring data protection within reports and dashboards.

To create calculated columns and measures, you can use the formula bar at the top of the model design window or the DAX editor. To set up row-level security formulas, you must log in to the Role Manager or the Role Management dialog box.

What is the CALCULATE function in Power BI?

According to the Microsoft Power BI documentation, the CALCULATE function is categorized under filter functions. It is defined as “evaluating an expression within a modified filter context.” An expression, which typically represents a measure, includes functions such as SUM, AVERAGE, and COUNT. This expression is evaluated in the context of one or more filters.

In Power BI, filters can be applied to reports simply using selectors (slicers), without the need to create a measure with the CALCULATE function. However, there are a number of scenarios in which using the CALCULATE function is more advantageous. It is especially effective when used as part of a larger function or calculation.

One of the most versatile functions for enriching your reports with more detailed insights is the CALCULATE function. This Power BI feature allows you to modify the calculation context within a measure, with the context defined by the environment in which the calculation takes place.

With Power BI's CALCULATE function, you can seamlessly switch to time-based calculations. This feature allows you to generate insightful, high-quality information using Power BI's diverse computing capabilities.

Need a hand with PowerBI reports?

Dev4Side Software specializes in creating customized reports through Microsoft Power BI, transforming complex data into intuitive dashboards and reports to support informed business decisions.

Operating vertically across the entire Microsoft Power Platform ecosystem, we have developed excellent expertise in Power BI, allowing us to offer business intelligence solutions that highlight critical insights and promote operational efficiency.

Find out how we can help you make the most of your data. Contact us to transform business information into concrete actions.

CALCULATE by Power BI: syntax

After analyzing what the CALCULATE Power BI function is, let's see its basic syntax below.

Calculate (<expression>[, <filter1>[, <filter2>[,...]]])

Power BI's CALCULATE function works by evaluating an expression within a modified filter context. The main topic defines the expression to be evaluated, while the additional arguments, which are optional, provide filters that can adapt the way in which the expression is evaluated.

Filters can be applied to change the filter context of an expression, allowing calculations based on particular conditions or subsets of data. This ability is especially useful for deriving values that meet specific criteria or for focusing on distinct segments of data.

For example, the following code calculates total sales for the year 2024, but specifically for the “Electronics” product category: “PythonCalculate (SUM (Sales [Amount]), Sales [Year] = 2024, Sales [Category] = “Electronics”).

In this example, SUM (Sales [Amount]) is the expression used to determine total sales. The Sales [Year] = 2024 and Sales [Category] = “Electronics” filters are applied to the expression to change the filter context and include only sales data for the year 2024 and for the Electronics category.

The result of this calculation will be the total sales for the Electronics category in the year 2024.

Power BI's CALCULATE function consists of two main elements:

  1. Expression: this part represents the aggregation component, formulated in a similar way to a measure, using functions such as SUM, AVERAGE and COUNT.
  2. Filters: this component allows you to define one or more filters that determine the context within which the aggregation is applied.

The CALCULATE function supports three types of filters:

  1. Boolean Filter Expressions: these are simple filters that evaluate to TRUE or FALSE.
  2. Filter Expressions on Tables: they are more complex filters that return a table of results.
  3. Filter Editing Functions: This category includes filters such as ALL and KEEPFILTERS, which offer greater control over the context of the applied filter.

You can include multiple filters in the filter component of the CALCULATE Power BI function, separating them with commas. These filters are evaluated collectively and their sequence does not affect the results.

You can manage how filters are evaluated using logical operators. Using the AND operator (`&&`), all specified conditions must be TRUE for the evaluation to be successful. This is also the default behavior for filters. In contrast, the OR operator (`||`) requires that at least one of the conditions be TRUE for the result to be returned.

How to use CALCULATE in Power BI?

To use the CALCULATE function in Power BI, start by opening Power BI Desktop. Next, go to the Data panel on the right side of the interface and choose the table where you want to create a new measure. Right-click on this table and select the option for a New Measure. For example, we'll add this measure to the Sales table.

If you prefer to avoid complex syntax, start by creating a Total Sales measure using the formula: SUM (Sales [SalesAmount]). Next, you can define your 2023 Sales measure like this:

2023 Sales = CALCULATE (SUM (Sales [SalesAmount]), 'Calendar' [Year] =2023)

If you prefer to avoid lengthy syntax, start by creating a Total Sales measure using the formula: `SUM (Sales [SalesAmount]) `. Then, you can define the 2023 Sales measure like this:

2023 Sales = CALCULATE ([Total Sales], 'Calendar' [Year] =2023)

After that, you can customize the look of your measurement in the Measurement Tools tab. For example, you can format it to display it as a currency with two decimals. If you then create a table that shows the product categories together with two measures - Total Sales and the new Sales measure 2023 - the latter will always be filtered to show sales for the year 2023.

Here are three important aspects of the formula.

The `<expression>` argument uses a measure called [Total Sales]. You can also use any formula that can define a measure, such as `SUM (Sales [SalesAmount]) `.

For the argument `<filter>`, let's not enclose 2023 in quotes because the Year column is numeric. If it were textual, you should write it as `"2023"`.

In this example, we only use a <filter>``, but you can include multiple filters within a single CALCULATE formula if necessary. Now that we've incorporated CALCULATE into a measure, let's explore how this function works.

Suppose we add a drop-down filter (slicer) that filters the table for the year 2020. In this case, the CALCULATE formula in Power BI will override this filter, showing sales for 2023 instead.

This happens because the `<filter>` arguments in the CALCULATE function are evaluated during the 'filtering' phase of calculating the measure. They modify the filter context provided by the view. This adjustment occurs before these filters are applied to the source tables and before the calculation phase begins.

In addition, the filter in the CALCULATE formula in Power BI adds an extra layer to the filter context. This new filter (Year = 2023) is combined with the existing one (ProductCategory). The result is the intersection of these two filters, showing sales for each product category specifically for the year 2023.

In summary, the CALCULATE function in Power BI allows you to change the context of your calculations on the data, giving you greater control over the analysis of your data.

CALCULATE by Power BI: practical examples

Until now we have explored the world of DAX functions and, specifically, the CALCULATE Power BI formula, its syntax and how to use it. Now, all we have to do is apply the formula in some practical examples and show the full potential of one of the most used formulas in Power BI.

E-Commerce Dataset Example

For this CALCULATE Power BI example, we will use an e-commerce dataset to which we can apply our formula.

This dataset includes details about each purchase made by customers, such as the country of origin, product description, date and time of purchase, and the quantity and price of each item purchased.

If we wanted to know how to compare Italy's total monthly revenue with that of the remaining countries, then we should proceed as follows.

To begin, we will establish two measurements using the CALCULATE function. Our first measure involves the application of a basic Boolean filter to calculate the total turnover specific to Italy. This will be done using the SUM function to aggregate the revenue data for that country.

Italy Revenue = CALCULATE (SUM ('Online Retail' [Revenue]),
 'Online Retail' [Country] = “Italy”)

The CALCULATE function is used to change the context in which the SUM function is executed. The SUM function, in turn, sums the values of the 'Revenue' column in the 'Online Retail' table.

The CALCULATE function requires two arguments: the first is the expression to be evaluated (such as the SUM function), and the second is a filter that alters the context in which this expression is evaluated.

In the code, the filter is `'Online Retail' [Country] = “Italy"`, which narrows the 'Online Retail' table to include only rows where the 'Country' column matches 'Italy'.

Therefore, the code calculates the total of the 'Revenue' column in the 'Online Retail' table, but it only includes the rows where the 'Country' column is set to 'Italy'. The result is then saved in a variable called 'Italy Revenue'.

Next, we'll build a comparable measure, but this time using the FILTER function. The FILTER function iterates over each row in the Country column and produces a table that includes only rows that meet the specified filter criteria. This approach is necessary because, unlike a simple TRUE or FALSE filter, FILTER returns a table with multiple values that satisfy the condition.

Non-Italy Revenue = CALCULATE (SUM ('Online Retail' [Revenue]),
 FILTER ('Online Retail',
 'Online Retail' [Country] <> “Italy”))

And that's it.

DAX formula from our example in the Power BI editor

If, on the other hand, you were wondering, considering the same e-commerce dataset, how to obtain the percentage of total revenue from Italy, know that this type of demand is frequently encountered by Power BI developers and users, making it an ideal scenario for applying the CALCULATE function.

To calculate the percentage of a total, we must first obtain the total value that is not affected by other filter contexts in the report. This is done using a filter modifier called the ALL function. By applying this function, we indicate which column should be completely ignored in terms of filtering during the calculation.

In this example, we want to determine the percentage of total revenue specifically for Italy. This requires that our calculation ignores any filters applied to the Country column.

Total Revenue = CALCULATE (SUM ('Online Retail' [Revenue]),
 ALL ('Online Retail' [Country]))

In this scenario, calculate the sum of the 'Revenue' column in the 'Online Retail' dataset, ignoring any filters applied to the 'Country' column through the use of the ALL function. This leads to the total revenue of the 'Online Retail' dataset, regardless of any country-specific filters.

Remember that the name of the variable 'Total Revenue' should be written without spaces, so it should be 'TotalRevenue'.

This is crucial because CALCULATE can operate within a filter context that is already applying a filter to Product [Color]. When using ALL in this scenario, it overwrites the existing filter on Product [Color] and applies the new filter specified within CALCULATE. This behavior is especially evident if you change the drop-down filter (slicer) from Brand to Color in the matrix.

With the established total revenue, we can now create a measure to display the percentage of total revenue. Since our focus is on Italy, we will still use the CALCULATE function, but this time applying a simple Boolean filter.

Italy% of Revenue = CALCULATE (SUM ('Online Retail' [Revenue])/[Total Revenue],
 'Online Retail' [Country] = “Italy”)

The '/ [Total Revenue] 'segment of the code divides the revenue for Italy by the total revenue of all the countries in the dataset. Meanwhile, the final part of the code, `'Online Retail' [Country] = “Italy"`, narrows the dataset to include only records from Italy.

Overall, this code calculates the percentage of revenue contributed by Italy within the 'Online Retail' dataset.

Now that you also know the total percentage of Italy's turnover, you would like to know what the cumulative daily turnover is, because analyzing the cumulative turnover can provide valuable insights into revenue trends. By tracking this cumulative revenue, it is possible to visually assess whether revenue growth has accelerated over time or has followed a more gradual increase.

To solve this query, we need to build a measure that combines the CALCULATE function with different filter functions: ALLSELECTED, FILTER, and an evaluation using the MAX function.

Cumulative Revenue = CALCULATE (SUM ('Online Retail' [Revenue]),
 FILTER (ALLSELECTED ('Online Retail' [InvoiceDate]),
 'Online Retail' [InvoiceDate] <= MAX ('Online Retail' [InvoiceDate])))
DAX formula from our example in the Power BI editor

The FILTER function is used to restrict the dataset based on a specified condition. In this case, the condition is that 'InvoiceDate' must be less than or equal to the maximum invoice date in the dataset. In the meantime, the ALLSELECTED function is used to eliminate any existing filters on the 'InvoiceDate' column.

In summary, the code calculates the total revenue for all dates up to and including the maximum invoice date in the dataset, thus obtaining the cumulative revenue.

Let's explore the meaning of these filters.

The FILTER function is critical because it evaluates each of the two specified filters on a line-by-line basis. Returns a table that includes only the rows where the conditions are met.

The ALLSELECTED function resets the filter to 'InvoiceDate' within the current query—as in the line chart shown below—while preserving any external filters applied, such as those coming from the selectors.

The MAX function is used in the evaluation to determine the maximum date in the query. We use this value to sum the revenue for all dates that are equal to or before the current date in the query.

Conclusions

The CALCULATE Power BI function greatly amplifies the capabilities and adaptability of data analysis and reporting. By changing the context of the filters when evaluating expressions, CALCULATE allows users to perform dynamic calculations and obtain more detailed insights from their datasets.

In this article, we explored the fundamentals of DAX, explored the syntax and application of the CALCULATE function in Power BI, and presented practical examples to illustrate its capabilities. From simple aggregations to complex calculations, CALCULATE's versatility and power make it a crucial tool for Power BI users.

In conclusion, the CALCULATE function is essential to unlock the full potential of Power BI. Its ability to adapt filter contexts and perform complex calculations makes it a cornerstone of advanced data modeling and analysis. Integrating CALCULATE into your DAX toolkit will pave the way for more in-depth data-driven decisions and more comprehensive reporting in Power BI.

FAQ on the CALCULATE function in Power BI

What is the CALCULATE function in Power BI?

The CALCULATE function is used to evaluate an expression in a modified filter context, making it essential for dynamic data analysis in Power BI.

How is CALCULATE different from other DAX functions?

Unlike other functions, CALCULATE can alter the filter context of the data being analyzed, allowing for more complex and customized calculations.

What is the syntax for CALCULATE?

The basic syntax is CALCULATE(<expression>, <filter1>, <filter2>, ...), where <expression> is the calculation to perform, and the filters adjust the context.

Can CALCULATE handle multiple filters?

Yes, you can apply multiple filters to refine the context for your calculations, which are evaluated collectively.

What are common use cases for CALCULATE?

CALCULATE is often used for time-based calculations, filtering data by specific conditions, and comparing metrics across different dimensions.

How do Boolean filters work with CALCULATE?

Boolean filters in CALCULATE return TRUE or FALSE, determining which data rows are included in the calculation.

How does CALCULATE work with context modification?

CALCULATE modifies the filter context within which an expression is evaluated, offering more precise control over what data is included in the calculation.

Get in touch with the team

Modern Work

The Modern Work team effectively and swiftly addresses IT needs, primarily focusing on software development. The technical staff is well-trained in implementing software projects using Microsoft technology stacks and is skilled in managing both agile and long-term projects.