Home >Database >Mysql Tutorial >How to Identify Consecutive Date Ranges in SQL?
To identify consecutive date ranges in a column containing a sequence of dates, SQL can be employed to efficiently extract the start and end dates of each distinct range.
Consider the following dataset:
InfoDate 2013-12-04 2013-12-05 2013-12-06 2013-12-09 2013-12-10 2014-01-01 2014-01-02 2014-01-03 2014-01-06 2014-01-07 2014-01-29 2014-01-30 2014-01-31 2014-02-03 2014-02-04
The goal is to extract the start and end dates of each consecutive date range, resulting in:
StartDate EndDate 2013-12-04 2013-12-06 2013-12-09 2013-12-10 2014-01-01 2014-01-03 2014-01-06 2014-01-07 2014-01-29 2014-01-31 2014-02-03 2014-02-04
A simplified and efficient SQL solution can be devised using the following steps:
The SQL query to achieve this is:
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)
The above is the detailed content of How to Identify Consecutive Date Ranges in SQL?. For more information, please follow other related articles on the PHP Chinese website!