在日期范围Oracle中生成开始日期和结束日期

时间:2014-08-01 21:28:58

标签: sql database oracle

我做了以下查询并得到以下输出。但是日期不应该是连续的,新的季度应该从第二天开始。

SELECT x.* , end_dt-st_dt FROM 
(SELECT 12-(LEVEL-1) AS Quater ,trunc(sysdate) - 90*LEVEL AS st_dt,trunc(sysdate) - 90*(LEVEL-1) AS end_dt
FROM dual
connect BY LEVEL <= 12
ORDER BY 1
) x

1   8/17/2011   11/15/2011  90
2   11/15/2011  2/13/2012   90
3   2/13/2012   5/13/2012   90
4   5/13/2012   8/11/2012   90
5   8/11/2012   11/9/2012   90
6   11/9/2012   2/7/2013    90
7   2/7/2013    5/8/2013    90
8   5/8/2013    8/6/2013    90
9   8/6/2013    11/4/2013   90
10  11/4/2013   2/2/2014    90
11  2/2/2014    5/3/2014    90
12  5/3/2014    8/1/2014    90

预期输出:

....
...
    10  11/2/2013   1/31/2014   90
    11  2/1/2014    5/2/2014    90
    12  5/3/2014    8/1/2014    90

1 个答案:

答案 0 :(得分:1)

这是你想要的吗?我不确定

SELECT x.* , end_dt-st_dt FROM 
(SELECT 12-(LEVEL-1) AS Quater ,
(CASE WHEN ( trunc(sysdate) - 90*LEVEL = TO_DATE('17-AUG-11','DD-MON-YY')) 
THEN trunc(sysdate) - 90*LEVEL
ELSE trunc(sysdate)+1 - 90*LEVEL
END) AS st_dt,trunc(sysdate) - 90*(LEVEL-1) AS end_dt
FROM dual
connect BY LEVEL <= 12
ORDER BY 1
) x;

我的输出:

  • 1 17-AUG-11 15-NOV-11 90
  • 2 16-NOV-11 13-FEB-12 89
  • 3 14-FEB-12 13-MAY-12 89
  • 4 14-MAY-12 11-AUG-12 89
  • 5 12-AUG-12 09-NOV-12 89
  • 6 10-NOV-12 07-FEB-13 89
  • 7 08-FEB-13 08-MAY-13 89
  • 8 09-MAY-13 06-AUG-13 89
  • 9 07-AUG-13 04-NOV-13 89
  • 10 05-NOV-13 02-FEB-14 89
  • 11 03-FEB-14 03-MAY-14 89
  • 12 04-MAY-14 01-AUG-14 89