如何通过
scenario
获取每年的行,这些行与每年的最新场景相关联,同时最多是前一个月(也存在未来预算和预测场景)
scenario
(VARCHAR)
a_year
(格式为 VARCHAR 'FY%y'
)例如:FY20、FY21、...FY24
a_month
(格式为 VARCHAR '%b'
)例如:一月、二月、...、十二月
amount
(双)
+----------------+------+-----+-----+
| 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 |
+----------------+------+-----+-----+
当每月更新月度预测/预算时,每个历史年份的每个场景都有 288 行。 (12 个预算和 12 个预测,每个包含 12 行。
如果预测上次更新是在 2024 年 2 月,预算是在 4 月,那么输出应仅包含 12 行,格式为:
+---------------------+------+-----+----+
| 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 | $$ |
+---------------------+------+-----+----+
我使用 CTE 来查找每种场景类型的最大 YearMonth
WITH CTE AS (
SELECT MAX(
a_year||CAST(EXTRACT(MONTH FROM to_date(Substring(scenario,1,3), 'Mon')) as VARCHAR(2) )
) as MaxYearMonth,
Substring(scenario,5,4) as ScenarioType
FROM Example
GROUP BY Substring(scenario,5,4)
)
SELECT *
FROM Example a
INNER JOIN CTE on CTE.MaxYearMonth = a.a_year||CAST(EXTRACT(MONTH FROM to_date(Substring(a.scenario,1,3), 'Mon')) as VARCHAR(2) )
AND CTE.ScenarioType= Substring(a.scenario,5,4)