Chapter 12: A Few Ideas: PowerPivot and DAX Solutions 367
Changes over Time
Another classic BI requirement is to show changes over time. For example, you may
wish to see increases and decreases in sales from one year to the next. The DAX Date
and Time functions are particularly useful in order to achieve such results. Some of
these functions require contiguous dates. Without contiguous dates, functions, such as
DATEADD() and SAMEPERIODLASTYEAR(), will either result in an error or produce
nonintuitive results. The example here uses ContosoRetailDW, as Northwind lacks
contiguous dates. You will need the DimDate, DimProduct, and FactSales tables.
Make sure that FactSales is related to both DimDate (on DateKey) and DimProduct
(on ProductKey). Add SalesAmount from FactSales to the Values drop-zone. Add
CalendarYear from DimDate to Column Labels and BrandName from DimProduct
to Row Labels. Interestingly, you will see that Adventure Works and Northwind supply
products to Contoso! The example that follows uses DATEADD() to retrieve sales
from the previous year and then compares the value to the current year to ascertain the
change in sales over time. You could also try PARALLELPERIOD(), if you wish. Here is
the DAX to work out a change in sales:
=SUM(FactSales[SalesAmount])-
CALCULATE(SUM(FactSales[SalesAmount]),DATEADD(DimDate[DateKey],-1,YEAR))
Moving Average
This example also uses ContosoRetailDW. The rows are from the DateKey in the
DimDate table, and the first column of values is the SalesAmount column from the
FactSales table. Figure 12-22 shows the result of a moving average measure. The formula
for the measure is:
=CALCULATE(SUM(FactSales[SalesAmount]),DATESBETWEEN(DimDate[Datekey],
FIRSTDATE(DATEADD(DimDate[Datekey],-2,DAY)),
LASTDATE(DimDate[Datekey])))/3
This is a three-day moving average. The divisor is 3, yet DATEADD() uses -2—that’s
going to return three dates including the current date. You can get rid of the first two
entries by testing for blanks. Northwind is not really suitable here as it lacks contiguous
dates.