Home >Database >Mysql Tutorial >How to Generate Dates Across Multiple Date Ranges in SQL?

How to Generate Dates Across Multiple Date Ranges in SQL?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-04 10:12:34663browse

How to Generate Dates Across Multiple Date Ranges in SQL?

Generating Dates between Multiple Date Ranges

The problem of generating dates between two given dates is quite common. However, when dealing with multiple date ranges, the solution can become more complex. This question on StackOverflow presents one such scenario and provides an elegant solution using an inline view and a recursive query:

select 
  A.ID, 
  A.START_DATE+delta 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 <= A.end_date
order by 1, 2

The inline view calculates a range of deltas from 1 to the maximum difference between the start and end dates of any range in the table using a recursive query. This range of deltas is then used in the main query to generate all the dates between the start and end dates of each range.

The query first joins the t_dates table with the inline view, generating all possible pairs of start dates and deltas. It then filters out those pairs where the resulting date would be beyond the end date of the corresponding range. Finally, the query sorts the results by ID and date.

This solution is flexible and can be used to generate dates for any number of date ranges. It leverages the power of recursive queries to provide a concise and efficient way to solve this problem.

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

Statement:
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