优化查找每年最大值、字符串、属性

问题描述 投票:0回答:1

如何通过

scenario
获取每年的行,这些行与每年的最新场景相关联,同时最多是前一个月(也存在未来预算和预测场景)

领域:

  • scenario
    (VARCHAR)

    • 区分预算或预测
      • 预测格式(Jan Fcst、Feb Fcst、...、Dec Fcst)
      • 预算格式(一月调整预算、二月调整预算、...十二月调整预算)
    • 预测和预算每月更新当年每个月(每个独特的预测包括 12 行(1 月 - 12 月)。
  • 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 | $$ |
+---------------------+------+-----+----+
sql postgresql optimization hive query-optimization
1个回答
0
投票

我使用 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)

小提琴

© www.soinside.com 2019 - 2024. All rights reserved.