How to Achieve dynamic data retrieval: Current month + 12 months prior using SQL in Dashboards
Hi All,
I am currently facing a challenge with my SQL code in dashboards and would greatly appreciate your help in finding a solution. The issue at hand is that I have hardcoded the code to pull data from tables, but now I need to modify it so that when a user selects a specific month (e.g., 2023M1), the dashboard displays data for the selected month as well as the 12 months prior to it.
To provide more context, here is the query I am currently using:
SELECT ISNULL(Name, 'Total |!SelectAcc!|') AS Name,
SUM(CASE WHEN Period = '2022M12' THEN |!SelectAcc!| END) AS '2022M12',
SUM(CASE WHEN Period = '2022M11' THEN |!SelectAcc!| END) AS '2022M11',
SUM(CASE WHEN Period = '2022M10' THEN |!SelectAcc!| END) AS '2022M10',
SUM(CASE WHEN Period = '2022M9' THEN |!SelectAcc!| END) AS '2022M9',
SUM(CASE WHEN Period = '2022M8' THEN |!SelectAcc!| END) AS '2022M8',
SUM(CASE WHEN Period = '2022M7' THEN |!SelectAcc!| END) AS '2022M7',
SUM(CASE WHEN Period = '2022M6' THEN |!SelectAcc!| END) AS '2022M6',
SUM(CASE WHEN Period = '2022M5' THEN |!SelectAcc!| END) AS '2022M5',
SUM(CASE WHEN Period = '2022M4' THEN |!SelectAcc!| END) AS '2022M4',
SUM(CASE WHEN Period = '2022M3' THEN |!SelectAcc!| END) AS '2022M3',
SUM(CASE WHEN Period = '2022M2' THEN |!SelectAcc!| END) AS '2022M2',
SUM(CASE WHEN Period = '2022M1' THEN |!SelectAcc!| END) AS '2022M1',
SUM(|!SelectAcc!|) As 'TOTAL'
FROM (
SELECT Name, |!SelectAcc!|, Period FROM Account_TABLE WHERE Period IN ('2022M12', '2022M11','2022M10', '2022M9','2022M8','2022M7', '2022M6','2022M5', '2022M4','2022M3', '2022M2','2022M1')
UNION
SELECT Name, |!SelectAcc!|, Period FROM Second_TABLE WHERE Period IN ('2022M12', '2022M11','2022M10', '2022M9','2022M8','2022M7', '2022M6','2022M5', '2022M4','2022M3', '2022M2','2022M1')
) AS a
GROUP BY Rollup (Name)
ORDER BY
CASE
WHEN ISNULL(Name, 'Total |!SelectAcc!|') = 'Total |!SelectAcc!|' THEN 1
Else 0
END,
ISNULL(Name, 'Total |!SelectAcc!|')
As you can see, the query currently involves hardcoding all the 12 months prior to the selected month, which is not an efficient and scalable approach.
I am looking for a solution that allows for dynamic retrieval of data, enabling the display of the current month and the 12 months preceding it. For example, if a user enters "2023M1," the dashboard should show data for 2023M1 as well as all the 12 months prior to it.
If anyone could provide guidance, suggestions, or insights on how to modify this query to achieve the desired dynamic retrieval of data, I would be immensely grateful.
Thank You,
Rithik