简体   繁体   中英

Generate start and end dates in a date range Oracle

I made the below query and getting the following output.But the dates should not be consecutive,the new quater should start with next day.

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

EXPECTED output :

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

Is this is what you want? I am not sure

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;

My output:

  • 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
  • The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM