How do I get the rows for each year by scenario
that are associated to the latest scenario for each year while being at-most prior month (future budgets & forecast scenarios exist as well)
Fields:
-
scenario
(VARCHAR)- Distinguishes between budget or forecast
- Format for forecasts (Jan Fcst, Feb Fcst, …, Dec Fcst)
- Format for budgets (Jan Adjusted Budget, Feb Adjusted Budget, … Dec Adjusted Budget)
- Forecast & Budget are updated every month for each month in current year (each unique forecast includes 12 rows (Jan – Dec).
- Distinguishes between budget or forecast
-
a_year
(VARCHAR in format'FY%y'
) Ex: FY20, FY21, … FY24- indicates year the forecast or budget applies to
-
a_month
(VARCHAR in format'%b'
) Ex: Jan, Feb, …, Dec- indicates the month the forecast or budget applies to
-
amount
(DOUBLE)
+----------------+------+-----+-----+
| Jan Fcst | FY24 | Jan | 100 |
+----------------+------+-----+-----+
| Jan Fcst | FY24 | ... | 150 |
+----------------+------+-----+-----+
| Jan Fcst | FY24 | Dec | 80 |
+----------------+------+-----+-----+
| Feb Fcst | FY24 | Jan | 110 |
+----------------+------+-----+-----+
| Feb Fcst | FY24 | ... | 180 |
+----------------+------+-----+-----+
| Feb Fcst | FY24 | Dec | 103 |
+----------------+------+-----+-----+
| Jan Adj Budget | FY24 | Jan | 120 |
+----------------+------+-----+-----+
| Jan Adj Budget | FY24 | ... | 90 |
+----------------+------+-----+-----+
| Jan Adj Budget | FY24 | Dec | 110 |
+----------------+------+-----+-----+
| Feb Adj Budget | FY24 | Jan | 130 |
+----------------+------+-----+-----+
| Feb Adj Budget | FY24 | ... | 200 |
+----------------+------+-----+-----+
| Feb Adj Budget | FY24 | Dec | 120 |
+----------------+------+-----+-----+
Each historical year has 288 rows per scenario when monthly forecasts/budgets are updated each month. (12 budgets & 12 forecasts, each containing 12 rows.
If the Forecast was last updated in Feb 2024 & Budget in Apr then the output should only include 12 rows in format:
+---------------------+------+-----+----+
| Feb Fcst | FY24 | Jan | $$ |
+---------------------+------+-----+----+
| Feb Fcst | FY24 | ... | $$ |
+---------------------+------+-----+----+
| Feb Fcst | FY24 | Dec | $$ |
+---------------------+------+-----+----+
| Apr Adjusted Budget | FY24 | Jan | $$ |
+---------------------+------+-----+----+
| Apr Adjusted Budget | FY24 | ... | $$ |
+---------------------+------+-----+----+
| Apr Adjusted Budget | FY24 | Dec | $$ |
+---------------------+------+-----+----+
2
Answers
I used a CTE to find the max YearMonth for each scenario type
fiddle
This solution uses DISTINCT ON
Fiddle