从Oracle中的日期获取季度的问题

时间:2019-03-24 04:48:35

标签: sql oracle date

我编写了一个查询,以使用sysdate获取当前年度和上一年季度的开始日期。

例如今天是一年的第一季度,因此我只想获取去年和今年第一季度的开始日期。 如果我在12月(第4季度),我想获得8个季度的开始日期(去年为4个季度,今年为4个)。

select b.dt,
       to_number(to_char(SYSDATE, 'Q')),
       to_number(to_char(b.dt, 'Q'))
  from dual a,
       (select add_months(trunc(ADD_MONTHS(TRUNC(SYSDATE, 'MM'), -12),
                                'yyyy'),
                          (rownum - 1) * 3) dt
          from all_objects
         where rownum <= 8
           and add_months(trunc(ADD_MONTHS(TRUNC(SYSDATE, 'MM'), -12),
                                'yyyy'),
                          (rownum - 1) * 3) <= SYSDATE
           and to_number(to_char(SYSDATE, 'Q')) >=
               to_number(to_char(add_months(trunc(ADD_MONTHS(TRUNC(SYSDATE,
                                                                   'MM'),
                                                             -12),
                                                  'yyyy'),
                                            (rownum - 1) * 3),
                                 'Q'))) b

此查询仅返回去年第一季度的开始日期。我预计也将获得今年第一季度的开始日期。

enter image description here

1 个答案:

答案 0 :(得分:2)

这是一个选择;查看代码中的注释。

SQL> alter session set nls_date_format = 'dd.mm.yyyy';

Session altered.

SQL> with
  2  -- this mimics SYSDATE
  3  today (datum) as
  4    (select date '&date_literal' from dual),
  5  -- which quarter does DATUM belong to? Find 1st day in "this" and "previous" year
  6  quart as
  7    (select trunc(datum, 'yyyy') this,
  8            trunc(add_months(datum, -12), 'yyyy') previous,
  9            to_char(datum, 'q') quart from today)
 10  -- the fina result
 11  select add_months(this, (level - 1) * 3) result
 12  from quart
 13  connect by level <= quart
 14  union all
 15  select add_months(previous, (level - 1) * 3) result
 16  from quart
 17  connect by level <= quart;
Enter value for date_literal: 2019-03-24

RESULT
----------
01.01.2019
01.01.2018

SQL> /
Enter value for date_literal: 2019-08-13

RESULT
----------
01.01.2019
01.04.2019
01.07.2019
01.01.2018
01.04.2018
01.07.2018

6 rows selected.

SQL>