# “Year to date” and “Last Year To Date” in MDX

To get “Year To Date” and “Last Year To Date” in MDX we can use the YTD function. To get “Last Year To Date” we also have to use the “ParallelPeriod” function. The “ParallelPeriod” gives us the same dates for an other period. In this case we switch back one year.

Here is a sample

```WITH MEMBER [Year To Date] AS
( Sum (
Ytd ( [Date].[Calendar].CurrentMember ),
[Measures].[Internet Sales Amount]
) )
MEMBER [Last Year To Date] AS
( Sum (
Ytd (
ParallelPeriod ( [Date].[Calendar].[Calendar Year], 1, [Date].[Calendar].CurrentMember )
),
[Measures].[Internet Sales Amount]
) )
MEMBER [Change] AS
divide ( [Measures].[Year To Date], [Last Year To Date] ),
FORMAT_STRING = 'Percent'
SELECT
{ [Measures].[Year To Date], [Measures].[Last Year To Date], [Measures].[Change] } ON 0,
[Date].[Calendar].[Date].& ON 1
```

And here is the result This code will work in Analysis Services Multidimensional. If you want to do the same for “Month to date”, “Quarter to date” or similar you can change YTD to MTD or QTD. If you plan to use week you should use an other hierarchy and then change to WTD.

I would recommend you to add this functionality as  calculations in the cube. There are several great scripts out there for you to copy. Such as DateTool by Marco Russo.

# Comparable day in MDX using “lag” or “ParallelPeriod”

In many companies people want to compare todays sales with the comparable date last year. To find out what date the comparable day is we usually goes 364 days back from today.

In our sample today is 14 february 2012. And to see what the comparable date is we can use this query in SQL.

```select '2012/02/14' as TodaysDate, DateName(dw, '2012/02/14') As 'DayName',
```

This will give this result To check the sales for these days in MDX we can use these queries:

```SELECT [Measures].[Internet Sales Amount] ON 0,
[Date].[Calendar].[Date].& ON 1

SELECT [Measures].[Internet Sales Amount] ON 0,
[Date].[Calendar].[Date].& ON 1

The final query that compares today sales can look like this (using “lag”)

```WITH MEMBER [Sales comparable day] AS
( [Date].[Calendar].CurrentMember .Lag ( 364 ),
[Measures].[Internet Sales Amount] ),
FORMAT_STRING = "Currency"
MEMBER [Percent change] AS
[Measures].[Internet Sales Amount] / [Measures].[Sales comparable day],
FORMAT_STRING = "Percent"
SELECT
{ [Measures].[Internet Sales Amount], [Measures].[Sales comparable day], [Measures].[Percent change] } ON 0,
[Date].[Calendar].[Date].& ON 1

Or this (using ParallelPeriod and Aggregate)

```WITH MEMBER [Sales comparable day] AS
Aggregate (
ParallelPeriod ( [Date].[Calendar].[Date], 364, [Date].[Calendar].CurrentMember ),
[Measures].[Internet Sales Amount]
)
MEMBER [Percent change] AS
[Measures].[Internet Sales Amount] / [Measures].[Sales comparable day],
FORMAT_STRING = "Percent"
SELECT
{ [Measures].[Internet Sales Amount], [Measures].[Sales comparable day], [Measures].[Percent change] } ON 0,
[Date].[Calendar].[Date].& ON 1 