SQL:按连续记录分组

Cra*_*rze 12 sql t-sql sql-server sql-server-2000

一个稍微棘手的SQL问题(我们正在运行SQL Server 2000).

我有下表,StoreCount -

WeekEndDate    StoreCount
2010-07-25     359
2010-07-18     359
2010-07-11     358
2010-07-04     358
2010-06-27     358
2010-06-20     358
2010-06-13     358
2010-06-06     359
2010-05-30     360
2010-05-23     360
2010-05-16     360
Run Code Online (Sandbox Code Playgroud)

我想把它变成以下输出 -

StartDate    EndDate       StoreCount
2010-07-18   2010-07-25    359
2010-06-13   2010-07-11    358
2010-06-06   2010-06-06    359
2010-05-16   2010-05-30    360
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我只想按顺序一起运行时对存储计数进行分组.

Pat*_*and 12

这里是罐头的一个踢,只有它可能有SS2k中没有的语法.它实际上写在Oracle上,因为我不再拥有那个版本的SS了.唯一的问题可能是选择了一个选择......(自从我使用SS2k以来已经有一段时间了,所以很难记住当时没有哪些功能.)

select min(weekenddate) as start_date, end_date, storecount
from (
select s1.weekenddate
     , (select max(weekenddate)
          from store_stats s2
         where s2.storecount = s1.storecount
           and not exists (select null
                             from store_stats s3
                            where s3.weekenddate < s2.weekenddate
                              and s3.weekenddate > s1.weekenddate
                              and s3.storecount <> s1.storecount)
       ) as end_date
     , s1.storecount
from store_stats s1
) result
group by end_date, storecount
order by 1 desc


START_DATE END_DATE   STORECOUNT
---------- ---------- ----------
2010-07-18 2010-07-25        359
2010-06-13 2010-07-11        358
2010-06-06 2010-06-06        359
2010-05-16 2010-05-30        360
Run Code Online (Sandbox Code Playgroud)