Sub topic 3
Moving Averages and Related DAX Time Patterns
Assume you know basic measures such as SUM and DIVIDE, relationships in a star schema, and how to use measures in Power BI visuals. Time intelligence works by changing the dates in the current filter context before evaluating a measure.
Moving averages
A moving average smooths daily or monthly changes. This measure averages daily sales over the 30 days ending at the last visible date:
Sales 30 Day Avg =
VAR LastDate = MAX ( 'Date'[Date] )
VAR Window =
DATESINPERIOD ( 'Date'[Date], LastDate, -30, DAY )
RETURN
AVERAGEX ( Window, [Total Sales] )DATESINPERIOD returns the date window. AVERAGEX evaluates [Total Sales] for each date and averages the results. A monthly average can instead divide a window total by its distinct month count.
Month to date and quarter to date
Use TOTALMTD and TOTALQTD when the report needs totals from the start of the current month or quarter:
Sales MTD = TOTALMTD ( [Total Sales], 'Date'[Date] )
Sales QTD = TOTALQTD ( [Total Sales], 'Date'[Date] )These functions respect the current year and other filters.
Shifting periods with DATEADD
DATEADD shifts the visible dates by a specified interval. This prior-year measure shifts the dates back one year:
Sales PY =
CALCULATE (
[Total Sales],
DATEADD ( 'Date'[Date], -1, YEAR )
)SAMEPERIODLASTYEAR is a readable alternative for the same common case. DATEADD is more flexible for shifting by months, quarters, or days.
Fiscal years that do not end in December
Pass the fiscal year-end date to TOTALYTD. This measure resets on June 30:
Sales YTD Fiscal =
TOTALYTD ( [Total Sales], 'Date'[Date], "6-30" )Blanking future and incomplete periods
A date table may extend beyond the latest sale. Cap the measure so a chart does not show a misleading flat line:
Sales YTD Capped =
VAR LastSaleDate =
CALCULATE ( MAX ( Sales[Order Date] ), ALL ( 'Date' ) )
RETURN
IF ( MAX ( 'Date'[Date] ) <= LastSaleDate, [Sales YTD] )Common pitfalls and how to check your measures
- The date table must contain every date without gaps.
- Mark the table as a date table and relate
'Date'[Date]to the fact table's date column. - Check whether the visual uses dates from the date table, not directly from the fact table.
- Test a measure in a matrix by year, month, and date.
- Confirm that a prior-year period actually exists before judging the result.
Exercise
Which function creates the date window for the 30-day moving average?
Show answer
DATESINPERIOD creates the window, and AVERAGEX evaluates and averages the measure over that window.