Home > Database > Mysql Tutorial > How Can I Generate Dates Across Multiple Date Ranges in Oracle?

How Can I Generate Dates Across Multiple Date Ranges in Oracle?

Linda Hamilton
Release: 2025-01-02 15:06:42
Original
941 people have browsed it

How Can I Generate Dates Across Multiple Date Ranges in Oracle?

Handling Multiple Date Ranges for Date Generation

Generating dates between two dates is commonly encountered in various programming scenarios. While generating dates for a single range is straightforward, extending this functionality to handle multiple ranges can pose challenges.

Consider the following table where each row represents a date range:

ID START_DATE END_DATE
101 April 1, 2013 April 10, 2013
102 May 10, 2013 May 12, 2013

The expected output should generate individual dates within each range:

ID Dates
101 April 1, 2013
101 April 2, 2013
... ...
101 April 10, 2013
102 May 10, 2013
102 May 11, 2013
102 May 12, 2013

Oracle provides an ingenious solution to achieve this result:

select 
  A.ID, 
  A.START_DATE + (delta - 1) dt
from 
  t_dates A, 
  (
     select level-1 as delta 
     from dual 
     connect by level-1 <= (
       select max(end_date - start_date) from t_dates
     )
  )
where A.START_DATE + (delta - 1) <= A.end_date
order by 1, 2;
Copy after login

The delta column employs Oracle's CONNECT BY hierarchy to generate a sequence of integers from 1 up to the maximum difference between end and start dates in the table. The A.START_DATE (delta - 1) expression increments the start date by the appropriate delta for each record in the results. The WHERE clause filters out results that exceed the current date range's end date.

Enjoy this elegant solution for generating dates across multiple ranges in Oracle!

The above is the detailed content of How Can I Generate Dates Across Multiple Date Ranges in Oracle?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template