How to Dynamically Compare Previous Periods in KPI Cards?
This article outlines the steps to dynamically compare previous period values within a KPI Card when filtering the date range using a date picker. This functionality allows for a more insightful analysis of data trends over time.
Steps to Implement
-
Create a Dashboard Parameter
- Create a dashboard parameter and link it to the date picker widget.
- Create a dashboard parameter and link it to the date picker widget.
-
Define Calculated Fields
- Within the imported data source, define the following calculated fields:
Expression Name Formula Purpose StartDateExp CAST(@{{:Parameter1.START}} AS Date)
Converts the Start Date from character to date format. EndDateExp CAST(@{{:Parameter1.END}} AS Date)
Converts the End Date from character to date format. YearFromStartDate YEAR([StartDateExp])
Retrieves the year from the Start Date. YearFromEndDate YEAR([EndDateExp])
Retrieves the year from the End Date. MonthDifference ([YearFromEndDate] * 12 + MONTH([EndDateExp])) - ([YearFromStartDate] * 12 + MONTH([StartDateExp])) + 1
Calculates the number of months between the selected date range. PrevStartDate `DATE_TRUNC(‘month’, [StartDateExp] - ([MonthDifference] PrevEndDate `DATE_TRUNC(‘month’, [EndDateExp] - ([MonthDifference] PreviousMonthRangeValue if([sale_date] between [PrevStartDate] and [PrevEndDate], [amount], NULL)
Retrieves the sale amount from the previous date range. SelectedMonthRangeValue if([sale_date] between [StartDateExp] and [EndDateExp], [amount], NULL)
Retrieves the sale amount from the selected date range.
Note: The above-calculated fields are designed for use with a PostgreSQL database. Adjustments may be necessary for other database systems.
- Add Widgets to the Dashboard
- Add the date picker and KPI Card widgets to the dashboard. Assign the dashboard parameter to the date picker and enable the date range.
4. Configure the KPI Card Widget
- Set the KPI Card widget to use “PreviousMonthRangeValue” as the Target Value and “SelectedMonthRangeValue” as the Actual Value.
Example Usecase
Once configured, the KPI Card will display the previous range’s value as the Target Value and the selected range’s value from the date picker as the Actual Value. For example, if a date range from August 1st, 2025, to August 31st, 2025, is selected, the Actual Value will represent the sales amount for this range, while the Target Value will be calculated based on the previous range (July 1st to July 31st).