【问题标题】:Convert financial year and financial quarter into year month将财政年度和财政季度转换为年月
【发布时间】:2019-05-30 23:14:17
【问题描述】:

我在一个表中有 2 列,Financial_Year 和 Financial_Quarter。数据示例如下:

Financial_Year  Financial_Quarter
2018/2019         2

我想生成名为“Year_month”的第三列,它是每个财政年度内季度的最后一个月,因此在上面的示例中,我希望 year_month 列显示为 201809。

有人知道如何在 Oracle SQL 中执行此操作吗?

【问题讨论】:

  • 请定义您的财政年度。
  • 您也许可以将季度乘以 3。如果您的财政年度不完善,您当然必须对此进行调整。
  • 那么,FINANCIAL_YEAR 列是一个字符串,对吧?格式是'2018/2019',两个数字用斜线隔开?那么,我是否正确理解 2018/2019 财政年度从 2018 年 4 月 1 日开始,到 2019 年 3 月 31 日结束?

标签: sql oracle


【解决方案1】:

假设 FINANCIAL_YEAR 列是一个字符串(由斜线分隔的两个数字),并且 2018/2019 财政年度从 2018 年 4 月 1 日开始,到 2019 年 3 月 31 日结束,您可以执行以下操作:

with
  test_data (financial_year, financial_quarter) as (
    select '2018/2019', 1 from dual union all
    select '2018/2019', 2 from dual union all
    select '2018/2019', 3 from dual union all
    select '2018/2019', 4 from dual
  )
select financial_year, financial_quarter,
       to_char(add_months(to_date(substr(financial_year, 1, 4) || '03', 'yyyymm'),
                          3 * financial_quarter), 'yyyymm') as year_month
from   test_data
;

FINANCIAL_YEAR  FINANCIAL_QUARTER  YEAR_MONTH
--------------  -----------------  ----------
2018/2019                       1  201806
2018/2019                       2  201809
2018/2019                       3  201812
2018/2019                       4  201903

另外,只是为了好玩,这里有一个不同的解决方案,它不使用任何日期计算 - 它都是基于字符串的。

select financial_year, financial_quarter,
       substr(financial_year, decode(financial_quarter, 4, 6, 1), 4) ||
       decode(financial_quarter, 1, '06', 2, '09', 3, '12', 4, '03') as year_month
from   test_data
;

【讨论】:

    【解决方案2】:

    我想有很多方法可以给这只猫剥皮,这里有一个

    SELECT CASE WHEN financial_quarter = '4' THEN SUBSTR(financial_year, 6, 4) || '03' 
           ELSE SUBSTR(financial_year, 1, 4) || LPAD((financial_quarter + 1) * 3, 2, '0')
           END
    FROM some_table
    

    如果financial_quarter 是数字,当然需要用 4 替换“4”

    【讨论】:

    • 非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 2023-01-10
    • 1970-01-01
    • 2014-04-26
    • 1970-01-01
    相关资源
    最近更新 更多