Skip to main content

Command Palette

Search for a command to run...

Power BI DAX: CALCULATE, SUM, PREVIOUSYEAR

Updated
2 min read
M

Mohamad's interest is in Programming (Mobile, Web, Database and Machine Learning). He is studying at the Center For Artificial Intelligence Technology (CAIT), Universiti Kebangsaan Malaysia (UKM).

CALCULATE ( SUM ( Sales[Sales] ), PREVIOUSYEAR ( dimDate[Date] ) )

Brief explanation

The CALCULATE() function in DAX is used to modify the filter context of an expression. It allows you to apply specific filters to your data before performing calculations, making it a powerful tool for dynamic and context-sensitive analysis.

How it works:

  1. Filter Context Modification (B): The filter context specified by B is applied first. This could be a filter condition, a time intelligence function like PREVIOUSYEAR, or any other context modifier.

  2. Expression Evaluation (A): Once the filter context is modified by B, the expression A is then evaluated within this new context.

Example

When you use CALCULATE(SUM(Sales[Sales]), PREVIOUSYEAR(dimDate[Date])), it performs the following:

  1. SUM(Sales[Sales]) • This part of the expression calculates the total sales amount from the Sales table.

  2. PREVIOUSYEAR(dimDate[Date]) • This function shifts the dates in the current context back by one year, returning a table of dates from the previous year.

  3. CALCULATE • The CALCULATE function modifies the filter context of the SUM calculation to include only the dates from the previous year, as specified by PREVIOUSYEAR.

Illustration

Let's say you have the following sales data:

DateSales
2023-01-01100
2023-01-02150
2023-01-03200
2024-01-01120
2024-01-02180
2024-01-03220

And your dimDate table has the following dates:

Date
2023-01-01
2023-01-02
2023-01-03
2024-01-01
2024-01-02
2024-01-03

If you use the DAX expression CALCULATE(SUM(Sales[Sales]), PREVIOUSYEAR(dimDate[Date])) in a report for January 2024, it will calculate the sum of sales for January 2023.

So, for January 2024, the calculation would be:

• 2024-01-01: Sum of sales on 2023-01-01 = 100

• 2024-01-02: Sum of sales on 2023-01-02 = 150

• 2024-01-03: Sum of sales on 2023-01-03 = 200

The result for each date in January 2024 would be:

DateSales (2024)Sales (2023)
2024-01-01120100
2024-01-02180150
2024-01-03220200

This allows you to compare the sales performance of the current period with the same period in the previous year.

21 views