Year to Date calculation in DAX

ByHariharan Rajendran

Year to Date calculation in DAX

This post explains how to achieve Year to Date calculation using DAX script.

In DAX, there is a pre-defend function available to get the Year to Date calculation. Also, for the quarter to date & month to date.

Those functions are

TOTALYTD()

TOTALQTD()

TOTALMTD()

Instead of using the pre-defend functions, we can use our own defined function like below. To achieve the YTD calculations, use the below functions

  1. CALCULATE
  2. FILTER
  3. ALL

Let us consider a field called “Total Sales”. We will be used the Total Sales & “Date” table.

YTDSales = CALCULATE([Total Sales],

                      FILTER(ALL(‘Date’),

                          ‘Date'[Calendar Year] = MAX(‘Date'[Calendar Year]) &&

                          ‘Date'[Date] <= MAX(‘Date'[Date])))

Compare the result TOTALYTD() with our script.

Explaining the script.

Let us consider that we are in row 2014 – March row on the above table.

YTDSales = CALCULATE([Total Sales],

FILTER(ALL(‘Date’),

‘Date'[Calendar Year] = MAX(‘Date'[Calendar Year]) &&

‘Date'[Date] <= MAX(‘Date'[Date])))

 

‘Date'[Date] <= MAX(‘Date'[Date]) => This line of code returns maximum date. In our case, It will return 31/3/2014

‘Date'[Calendar Year] = MAX(‘Date'[Calendar Year]) => This line of code returns maximum year.  In our case, it will return 2014

ALL(‘Date’) => This line of code returns all the dates from date table.

FILTER(ALL(‘Date’),

‘Date'[Calendar Year] = MAX(‘Date'[Calendar Year]) &&

‘Date'[Date] <= MAX(‘Date'[Date])))

The above line of codes returns, current row year and last date of the current row month.

 

About the Author

Hariharan Rajendran author

Hariharan Rajendran is a Microsoft Certified Trainer and Lead BI Solutions Consultant with 8+ years of experience in Database, BI and Azure platforms. Hariharan is also an active community leader, speaker & organizer and leads the Microsoft PUG (Power BI User Group – Chennai), SQLPASS Power BI Local Group – Chennai and an active speaker in SQL Server Chennai User Group and also a leader in Data Awareness Program worldwide events. Hariharan also frequently blogs (www.dataap.org/blog), provides virtual training (on ad-hoc basis) on Microsoft Azure, Database Administration, Power BI and database development to worldwide clients/audience.

Comments Are Closed!!!