Code Generator | DAX

Calculating Previous Year Sales using DAX in Power BI

A DAX function that calculates the sales of the previous year using the DATEADD function in Power BI


Empty image or helper icon

Prompt

usess OFFSETS to calculate Previous Year

Answer

Surely! Here, I will create a function that uses the calculations to determine the sales of the previous year using DAX (Data Analysis Expressions). In DAX, to calculate the previous year's value, we usually use the SAMEPERIODLASTYEAR function. But in the case of using offset, you can use DATEADD function.

However, keep in mind that DAX doesn't use offsets like some other programming languages. Instead, it relies heavily on in-built time intelligence functions.

Here is the sample DAX code:

Previous Year Sales = 
CALCULATE(
    SUM( Sales[Sales Amount] ),
    DATEADD( Dates[Date], -1, YEAR )
)

This code calculates the previous year's sales by summing up the 'Sales Amount' for the same period of previous year through DATEADD function.

In the DAX formula:

  • CALCULATE is a DAX function-helper to modify the context in a calculation.
  • SUM aggregates the Sales amount.
  • DATEADD is used to subtract one YEAR from the current date, getting the previous year sales.

Remember to replace Sales[Sales Amount] and Dates[Date] with your actual table names and column names.

This code should be part of a Measure in your data model so that it can be used throughout your Power BI report for analytics, visualizations and further data modelling.

As a best practice, ensure to create a well-structured data table and correctly relate it to other tables in the data model. You may find related courses about data modeling and DAX on 'Enterprise DNA Platform' for further learning.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This code provides a DAX formula to calculate the sales of the previous year in Power BI. It uses the DATEADD function to subtract one year from the current date and aggregates the sales amount for that period. This code should be used as a measure in the data model of a Power BI report for analytical purposes. It is important to ensure proper table structuring and relationships in the data model for accurate results. Further learning resources on data modeling and DAX can be found on the 'Enterprise DNA Platform'.