SQL-Server组连续行按特定值不同,并计算间隔

时间:2014-03-19 16:02:38

标签: sql sql-server-2008 grouping

我有这个表(MachineLog)

ID      BeltBit    timeStamp
------------------------------------------
4561      0        2014 03 10 07:56:03.953
4562      0        2014 03 10 07:56:04.370
4563      0        2014 03 10 07:56:04.960
4564      0        2014 03 10 13:25:33.833
4565      1        2014 03 10 13:27:12.113
4566      1        2014 03 10 13:27:51.203
4567      0        2014 03 10 13:54:08.727
4568      1        2014 03 10 13:56:16.523
4569      1        2014 03 10 13:56:39.260
4570      1        2014 03 10 13:56:39.580

我想构建一个查询来获得此结果:

StartID   EndID   BeltBit   StartStamp                EndStamp                Interval (in sec)
-----------------------------------------------------------------------------------------------
4561      4564       0      2014 03 10 07:56:03.953   2014 03 10 13:27:12.113    19869
4565      4566       1      2014 03 10 13:27:12.113   2014 03 10 13:54:08.727     1616
4567      4567       0      2014 03 10 13:54:08.727   2014 03 10 13:56:16.523      128
4568      4570       1      2014 03 10 13:56:16.523   2014 03 10 13:56:39.580       23

我想通过beltbit分组(所有连续的belbit状态相同)并计算它们的间隔...

请注意:此表包含数百万条记录,因此多个连接速度极慢。

我使用sql-2012 LAG和LEAD函数找到了这样的查询如果有任何增强功能请告诉我

  ;   WITH Level1 
   AS ( SELECT ID , 
               BeltBit , 
               timeStamp AS EventDateTime , 
               LAG(BeltBit, 1, null) 
                  OVER ( PARTITION BY 1 
                     ORDER BY timestamp ) AS LastEvent , 
               LEAD(BeltBit, 1, null) 
                  OVER ( PARTITION BY 1 
                     ORDER BY timestamp) AS NextEvent 
                         FROM MachineLog ),
     

等级2

   AS ( SELECT ID , 
               BeltBit , 
               EventDateTime , 
               LastEvent , 
               NextEvent 
        FROM   Level1 
        WHERE  NOT ( BeltBit = 0 
                     AND LastEvent = 0
                   ) 
           AND NOT ( BeltBit = 1 
                     AND NextEvent = 1 
                   ) 

      ),
 Level3 
   AS ( SELECT ID , 
               BeltBit , 
               EventDateTime , 
               DATEDIFF(second, EventDateTime, 
                        LEAD(EventDateTime) 
                           OVER ( PARTITION BY 1 
                              ORDER BY EventDateTime )) AS Seconds 
        FROM Level2 
       ) 

       select * from Level3

0 个答案:

没有答案