Home > Database > Mysql Tutorial > How to Generate All Dates Within Multiple Date Ranges Using SQL?

How to Generate All Dates Within Multiple Date Ranges Using SQL?

Mary-Kate Olsen
Release: 2025-01-04 22:32:40
Original
181 people have browsed it

How to Generate All Dates Within Multiple Date Ranges Using SQL?

Generating Dates Between Multiple Date Ranges

When dealing with multiple date ranges, generating all dates within these ranges can be a challenge. Let's explore an efficient solution that handles this scenario.

The provided input consists of two date ranges:

ID  START_DATE      END_DATE 
101 April, 01 2013  April, 10 2013 
102   May, 10 2013    May, 12 2013
Copy after login

Our goal is to generate an output table that lists all dates within these ranges:

ID  Dates
101 April, 01 2013 
101 April, 02 2013  
101 April, 03 2013  
101 April, 04 2013  
101 April, 05 2013  
101 April, 06 2013  
101 April, 07 2013  
101 April, 08 2013  
101 April, 09 2013  
101 April, 10 2013  
102   May, 10 2013  
102   May, 11 2013  
102   May, 12 2013
Copy after login

To achieve this, we can utilize the following SQL 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
Copy after login

The query generates all possible date differences within the maximum date range and then adds them to each start date to produce the desired output.

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

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