You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于d_period字段的月份前缀提取年度最晚月份数据?

解决方法:基于月份缩写提取年度最晚数据

你的思路方向是对的——要比较月份先后,必须把英文缩写转换成数字月份才能准确排序。下面是具体实现方案,不用单独创建永久映射表,用临时表或者内置函数都能搞定:

方法一:临时映射表 + 聚合筛选(适配多数SQL方言)

  1. 用CTE生成月份缩写到数字的临时映射,再关联主表找到最大月份:
WITH month_mapping AS (
    SELECT 'Jan' AS month_abbr, 1 AS month_num UNION ALL
    SELECT 'Feb' AS month_abbr, 2 AS month_num UNION ALL
    SELECT 'Mar' AS month_abbr, 3 AS month_num UNION ALL
    SELECT 'Apr' AS month_abbr, 4 AS month_num UNION ALL
    SELECT 'May' AS month_abbr, 5 AS month_num UNION ALL
    SELECT 'Jun' AS month_abbr, 6 AS month_num UNION ALL
    SELECT 'Jul' AS month_abbr, 7 AS month_num UNION ALL
    SELECT 'Aug' AS month_abbr, 8 AS month_num UNION ALL
    SELECT 'Sep' AS month_abbr, 9 AS month_num UNION ALL
    SELECT 'Oct' AS month_abbr, 10 AS month_num UNION ALL
    SELECT 'Nov' AS month_abbr, 11 AS month_num UNION ALL
    SELECT 'Dec' AS month_abbr, 12 AS month_num
),
latest_month_info AS (
    SELECT MAX(mm.month_num) AS latest_month
    FROM your_table t
    JOIN month_mapping mm ON LEFT(t.d_period, 3) = mm.month_abbr
)
SELECT t.Forecast, t.Budget, t.Actuals, t.d_period
FROM your_table t
JOIN month_mapping mm ON LEFT(t.d_period, 3) = mm.month_abbr
JOIN latest_month_info lmi ON mm.month_num = lmi.latest_month;

如果你的SQL支持MAXBY(),可以把latest_month_info部分替换成用MAXBY()直接关联月份数字,逻辑是相通的。

方法二:用内置函数直接转换月份(适配PostgreSQL、Oracle等)

如果所用SQL支持解析月份缩写的内置函数,无需手动做映射表:

WITH ranked_data AS (
    SELECT 
        Forecast, Budget, Actuals, d_period,
        -- 将月份缩写转为日期后提取月份,再倒序排名
        RANK() OVER(ORDER BY TO_DATE(LEFT(d_period,3), 'Mon') DESC) AS rnk
    FROM your_table
)
SELECT Forecast, Budget, Actuals, d_period
FROM ranked_data
WHERE rnk = 1;

关于SPLIT的说明

如果d_period格式是Jan-2024这类带分隔符的,用SPLIT(d_period, '-')[0]提取月份缩写也可以,和LEFT(d_period,3)效果一致,根据字段实际格式选择即可。

内容的提问来源于stack exchange,提问作者urdearboy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 05:06:28