(列)GatherDate        (列)speed       
2013-10-19 08:00:41 0.0
2013-10-19 08:10:30 0.0
2013-10-19 08:20:30 0.0
2013-10-19 08:30:30 NULL
2013-10-19 08:50:30 0.0
2013-10-19 09:00:30 0.0
2013-10-19 09:07:30 0.0
2013-10-19 09:08:30 11.0
2013-10-19 09:09:30 22.0
得出一个指定时间间隔(如10分钟,大于十分钟则归到下一时间段)且速度一直为0 表
(列)起始时间              (列)终止时间           (列)停滞时间
2013-10-19 08:00:41 2013-10-19 08:20:30          19
2013-10-19 08:50:30 2013-10-19 09:07:30          17sql语句数据

解决方案 »

  1.   


    create table hq
    (GatherDate varchar(30),speed decimal(5,1))insert into hq
     select '2013-10-19 08:00:41', 0.0 union all
     select '2013-10-19 08:10:30', 0.0 union all
     select '2013-10-19 08:20:30', 0.0 union all
     select '2013-10-19 08:30:30', NULL union all
     select '2013-10-19 08:50:30', 0.0 union all
     select '2013-10-19 09:00:30', 0.0 union all
     select '2013-10-19 09:07:30', 0.0 union all
     select '2013-10-19 09:08:30', 11.0 union all
     select '2013-10-19 09:09:30', 22.0
    with t as
    (select GatherDate,
            case when speed=0.0 then 1 else 0 end 'x',
            row_number() over(order by getdate()) 'rn'
     from hq)
    select min(GatherDate) '起始时间',
           max(GatherDate) '终止时间',
           datediff(mi,min(GatherDate),max(GatherDate)) '停滞时间'
    from
    (select a.GatherDate,
            a.rn-row_number() over(order by a.rn) 'rn'
     from t a where a.x=1) t
    group by rn/*
    起始时间                           终止时间                           停滞时间
    ------------------------------ ------------------------------ -----------
    2013-10-19 08:00:41            2013-10-19 08:20:30            20
    2013-10-19 08:50:30            2013-10-19 09:07:30            17(2 row(s) affected)
    */