Home > Database > Mysql Tutorial > How to Identify and Extract Consecutive Date Ranges in SQL?

How to Identify and Extract Consecutive Date Ranges in SQL?

Mary-Kate Olsen
Release: 2025-01-03 05:34:38
Original
131 people have browsed it

How to Identify and Extract Consecutive Date Ranges in SQL?

Identifying Consecutive Date Ranges in SQL

Question:

You need to extract consecutive date ranges from a table containing a single column of unsorted dates. These ranges represent segments of time that require start and end dates to fill a calendar object accurately.

Solution:

Approach:

To solve this problem using SQL, we can employ the "gaps-and-islands" method. This method groups consecutive dates by their difference from their row number, as this value remains constant for each consecutive sequence. We then use the MIN() and MAX() functions to extract the start and end dates of each group.

SQL Query:

WITH t AS (
  SELECT InfoDate d,ROW_NUMBER() OVER(ORDER BY InfoDate) i
  FROM @d
  GROUP BY InfoDate
)
SELECT MIN(d),MAX(d)
FROM t
GROUP BY DATEDIFF(day,i,d)
Copy after login

Explanation:

  • The WITH clause creates a common table expression (CTE) named t.
  • The CTE selects the InfoDate column d and the row number i for each row in the original table @d.
  • The data is grouped by InfoDate to ensure uniqueness within each consecutive sequence.
  • The SELECT statement calculates the minimum and maximum dates for each group, representing the start and end dates of consecutive ranges, respectively.
  • The DATEDIFF() function is used to calculate the difference between the row number and the date, which remains constant within each consecutive sequence, effectively grouping consecutive dates together.

Output:

The resulting table should contain the following columns:

  • StartDate
  • EndDate

This output provides the start and end dates for each consecutive date range, allowing you to populate your calendar object with the necessary date information.

The above is the detailed content of How to Identify and Extract Consecutive Date Ranges in SQL?. 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