SQL Server 2008 实现连续数据分组统计

分类:DataBase
2016-12-21 15:10 阅读(?)评论(0)
表结构如下:
ID    Name    ComeDate    Status
--------------------------------------------------
1      Grim    2016-12-01      0
2      Grim    2016-12-02      0
3      Grim    2016-12-03      0
4      Grim    2016-12-04      1
5      Grim    2016-12-05      1
6      Grim    2016-12-06      1
7      Grim    2016-12-07      0
8      Grim    2016-12-08      0

需要的结果:
Name    Status    StartDate    EndDate
--------------------------------------------------
Grim        0     2016-12-01  2016-12-03
Grim        1     2016-12-04  2016-12-06
Grim        0     2016-12-07  2016-12-08

建表sql:
create table PersonDetail
(
ID int identity(1,1) primary key,
Name nvarchar(10) not null,
ComeDate date  not null,
[Status] bit  not null
)
go

insert PersonDetail (Name, ComeDate, [Status])
values
('Grim', '2016-12-01', 0),
('Grim', '2016-12-02', 0),
('Grim', '2016-12-03', 0),
('Grim', '2016-12-04', 1),
('Grim', '2016-12-05', 1),
('Grim', '2016-12-06', 1),
('Grim', '2016-12-07', 0),
('Grim', '2016-12-08', 0)

表数据如下:









用的SQL Server 2008,没有Lag分析函数。

实现:
下面的SQL循环可以实现,但是比较麻烦:
;with PrevNextLoop
as
(
        select A.ID, A.Name, A.Status, A.ComeDate as PrevDate, A.ComeDate as NextDate
        from PersonDetail A

        union all
        select A.ID, A.Name, A.Status, PrevDate, B.ComeDate as NextDate
        from PrevNextLoop A
        join PersonDetail B on A.Name = B.Name and A.Status = B.Status and DATEADD(d, 1, A.NextDate) = B.ComeDate

        union all
        select A.ID, A.Name, A.Status, B.ComeDate as PrevDate, NextDate
        from PrevNextLoop A
        join PersonDetail B on A.Name = B.Name and A.Status = B.Status and DATEADD(d, -1, A.PrevDate) = B.ComeDate
)
, FirstLastLoop
as
(
        select ID, MIN(PrevDate) as FirstDate, MAX(NextDate) as LastDate from PrevNextLoop group by ID
)

select A.Name, A.Status, FirstDate, LastDate
from PersonDetail A
join FirstLastLoop B on A.ID = B.ID
group by A.Name, A.Status, FirstDate, LastDate
order by FirstDate
 
表  情:
加载中...
 

请各位遵纪守法并注意语言文明