oracle PL/SQL --基于频率的下一个日期

txu3uszq  于 2023-05-28  发布在  Oracle
关注(0)|答案(2)|浏览(122)

我正在寻找一个oracle函数或程序来计算下一个日期的基础上Input DateFrequency(Yearly,half yearly, Quarterly )
举个例子

Input Date     Frequency    Next Occurrence Date
1-Jan-2016     Quarterly     1-Apr-2016
1-Jan-2016     yearly        1-Jan-2017
bis0qfac

bis0qfac1#

查看Oracle函数ADD_MONTHS( date, number_months )以获得月度、季度和年度结果。
例如,下一个季度将是3个月。因此,如果输入日期是第一季度,则可以用途:

ADD_MONTHS( 01-JAN-2016, 3 )

才能拿到下一个季度
示例SQL:

select TO_DATE('01-JAN-2016', 'DD-MON-YYYY') as "Input Date",
       'Quarterly' as "Frequency",
       ADD_MONTHS(TO_DATE('01-JAN-2016', 'DD-MON-YYYY'), 3) as "Next Occurrence Date"
from dual
union
select TO_DATE('01-JAN-2016', 'DD-MON-YYYY') as "Input Date",
       'Yearly' as "Frequency",
       ADD_MONTHS(TO_DATE('01-JAN-2016', 'DD-MON-YYYY'), 12) as "Next Occurrence Date"
from dual
;

结果:

Input Date         Frequency Next Occurrence Date
------------------ --------- ------------------
01-JAN-16          Quarterly 01-APR-16
01-JAN-16          Yearly    01-JAN-17
slmsl1lt

slmsl1lt2#

扩展@tale852150的答案,你可以使用case表达式将频率转换为要添加的月数,假设你有一个已知的可能值列表:

add_months(input_date, case frequency
  when 'Quarterly' then 3
  when 'Half yearly' then 6
  when 'Yearly' then 12 else 0 end

快速演示:

with t (input_date, frequency) as (
  select date '2016-01-01', 'Quarterly' from dual
  union all select date '2016-01-01', 'Half yearly' from dual
  union all select date '2016-01-01', 'Yearly' from dual
)
select input_date, frequency,
  add_months(input_date, case frequency
    when 'Quarterly' then 3
    when 'Half yearly' then 6
    when 'Yearly' then 12 else 0 end) as next_occurrence_date
from t;

INPUT_DATE FREQUENCY   NEXT_OCCURRENCE_DATE
---------- ----------- --------------------
2016-01-01 Quarterly   2016-04-01          
2016-01-01 Half yearly 2016-07-01          
2016-01-01 Yearly      2017-01-01

相关问题