π Show Days Before or After a Selected Date in Power BI Using DAX
Have you ever wanted to dynamically show data for a number of days before or after a date selected by a user in Power BI?
In this article, Iβll show you how to:
- Select a date with a slicer
- Use a what-if parameter to choose a dynamic day range
- Calculate and display values before or after the selected date using DAX
Letβs get started with a hands-on walkthrough using a real Power BI model!
π Problem Statement
You want to analyze data like sales trends, logins, or energy consumption from a few days before or after a date selected by the user.
For example:
- If the user selects
June 10, 2024and chooses5as the number of days: - Show values from
June 5 to June 9(before) - Or from
June 11 to June 15(after)
This canβt be done natively with slicers. But with a little DAX and Power BI magic β we can do it!
π§± Step 1: Build a Date Table
Make sure you have a proper date table in your model.
DateTable = CALENDARAUTO()Once created:
- Mark it as a date table in Model view.
- Build a relationship between
DateTable[Date]and your fact table's date column.
πΌοΈ [Insert screenshot: Date table in Data view]
ποΈ Step 2: Create a What-If Parameter
Go to the Power BI ribbon:
Modeling β New Parameter β Fields:
- Name:
Day Offset - Data type: Whole number
- Minimum: 1
- Maximum: 30
- Increment: 1
Power BI will create:
- A DayOffset table
- A slicer for user input
π Step 3: Create a Date Slicer
Drag DateTable[Date] into a slicer visual.
Set it to:
- Dropdown
- Single-select only
This allows the user to select one specific date.
π§ Step 4: Capture the Selected Date
Create a DAX measure:
SelectedDate = SELECTEDVALUE(DateTable[Date])This will help us reference the selected date dynamically.
π Step 5: Create Measures for Before/After Periods
πΉ Sum for N Days Before the Selected Date
Sales_Before_N_Days =
VAR N = SELECTEDVALUE('DayOffset'[DayOffset])
RETURN
CALCULATE(
SUM('Sales'[SalesAmount]),
FILTER(
ALL('Sales'),
'Sales'[Date] < [SelectedDate] &&
'Sales'[Date] >= [SelectedDate] - N
)
)πΈ Sum for N Days After the Selected Dat
Sales_After_N_Days =
VAR N = SELECTEDVALUE('DayOffset'[DayOffset])
RETURN
CALCULATE(
SUM('Sales'[SalesAmount]),
FILTER(
ALL('Sales'),
'Sales'[Date] > [SelectedDate] &&
'Sales'[Date] <= [SelectedDate] + N
)
)π Step 6: Create Dynamic Visuals
- Card Visuals to display:
- Total Sales before selected date
- Total Sales after selected date
- Line or Area Chart:
- X-axis:
DateTable[Date] - Y-axis:
Sales[SalesAmount] - Apply visual-level filters using DAX logic (or add custom date range logic in measures)
