Transferred from: http://bbs.csdn.net/topics/360019248
How can I get the starting and ending dates for each successive date and the number of days and the days from the last end of the previous period, could I use a SQL implementation?
Note: The database environment is SQL Server 2000
CREATE TABLE tmptable (RQ datetime) Goinsert tmptable values (' 2010.1.1 ') Insert tmptable values (' 2010.1.2 ') insert Tmptable values (' 2010.1.3 ') Insert tmptable values (' 2010.1.6 ') Insert tmptable values (' 2010.1.7 ') Insert tmptable values (' 2010.1.10 ') Insert tmptable values (' 2010.1.11 ') Insert tmptable values (' 2010.1.12 ') Insert tmptable values (' 2010.1.19 Insert tmptable values (' 2010.1.20 ') Insert tmptable values (' 2010.1.22 ') Insert tmptable values (' 2010.1.23 ') insert Tmptable values (' 2010.1.28 ') go---desired results-current period Start date the current end date lasts days from previous period days--2010.1.1 2010.1.3 3 0-- 2010.1.6 2010.1.7 2 3--2010.1.10 2010.1.12 3 3--2010.1.19 2010.1.20 2 7 --2010.1.22 2010.1.23 2 2--2010.1.28 2010.1.28 1 5drop table Tmptablego
A sentence of SQL implementation
Select Current Period Start date =min (RQ), current period termination date =max (RQ), duration =max (ID1)-min (ID1) +1, from previous period days =case A.id1-a.id2 when-1 then 0 else Max ( DateDiff (D,RQ2,RQ)) End from ( select Id1=datediff (d, ' 2010-01-01 ', RQ), id2= (select COUNT (1) from Tmptable where RQ & lt;= A.rq), rq2= (select Max (RQ) from Tmptable where RQ < A.RQ), * from Tmptable a) Agroup by a.id1-a.id2/* Current Period Start date termination Date lasts days from previous period--------------------------------------------------------------------2010-01-01 00:00:00.000 2010-01-03 00:00:00.000 3 02010-01-06 00:00:00.000 2010-01-07 00:00:00.000 2 32010-01-10 00:00:00.000 2010-01-12 00:00:00.000 3 32010-01-19 00:00:00.000 2010-01-20 00:00:00.000 2 72010-01-22 00:00:00.000 2010-01-23 00:00:00.000 2 22010-01-28 00:00:00.000 2010-01-28 00:00:00.000 1 5 Warning: aggregation or other SET The operation eliminated null values. (6 rows affected) */
SQL Classic problem finding consecutive dates and consecutive days