季度中的月份序列号



我想通过 sql 确定其季度中的月份序列号

我找到了这段代码,但一周:

SELECT TO_CHAR( SYSDATE, 'YYYY-"Q"Q-"W"' )
     || ( 7 + TRUNC( SYSDATE + 1, 'IW' ) - TRUNC( TRUNC( SYSDATE, 'Q' ) + 1, 'IW' ) ) / 7
         AS "Current Time"
FROM DUAL;

这将为您提供一个从 1-3 的数值,表示季度内的月份值:

select case mod(to_number(to_char(sysdate, 'MM')), 3)
         when 0 then 3
         when 1 then 1
         when 2 then 2
       end as month_in_quarter
  from dual;

它使用模数 (mod( 函数来获取 0 - 2 之间的值。然后将 0 转换为 3,因为您希望 3 月、6 月、9 月和 12 月为 3,而不是 0。

从数字上看,Q1的第一个月是1;Q2的第一个月是4;依此类推。因此,当前季度中的月份是 mod(<month> - 1, 3) + 1 ,进行调整,这样您就不会最终得到零月(如@GriffeyDog所指出的那样(。所以你可以做到:

SELECT TO_CHAR(SYSDATE, 'YYYY-"Q"Q-"M"')
  || (MOD(EXTRACT(MONTH FROM SYSDATE) - 1, 3) + 1) AS "Current Time" 
FROM DUAL;
Current Time                                     
-------------------------------------------------
2017-Q2-M1

检查一系列日期:

with t as (
  select add_months(trunc(sysdate, 'mm'), level - 6) as dt
  from dual
  connect by level < 20
)
select dt, to_char(dt, 'YYYY-"Q"Q-"M"')
  || (mod(extract(month from dt) - 1, 3) + 1) as "Current Time" 
from t;
DT         Current Time                                     
---------- -------------------------------------------------
2016-11-01 2016-Q4-M2                                       
2016-12-01 2016-Q4-M3                                       
2017-01-01 2017-Q1-M1                                       
2017-02-01 2017-Q1-M2                                       
2017-03-01 2017-Q1-M3                                       
2017-04-01 2017-Q2-M1                                       
2017-05-01 2017-Q2-M2                                       
2017-06-01 2017-Q2-M3                                       
2017-07-01 2017-Q3-M1                                       
2017-08-01 2017-Q3-M2                                       
2017-09-01 2017-Q3-M3                                       
2017-10-01 2017-Q4-M1                                       
2017-11-01 2017-Q4-M2                                       
2017-12-01 2017-Q4-M3                                       
2018-01-01 2018-Q1-M1                                       
2018-02-01 2018-Q1-M2                                       
2018-03-01 2018-Q1-M3                                       
2018-04-01 2018-Q2-M1                                       
2018-05-01 2018-Q2-M2                                       

最新更新