SQL Server将不同于特定值的连续行分组,并计算间隔
我有这张桌子 我想构建一个查询以获得以下结果:SQL Server将不同于特定值的连续行分组,并计算间隔,sql,sql-server-2008,grouping,Sql,Sql Server 2008,Grouping,我有这张桌子 我想构建一个查询以获得以下结果: StartID EndID BeltBit StartStamp EndStamp Interval (in sec) ----------------------------------------------------------------------------------------------- 4561 4564 0 2014 0
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
我想分组的贝尔特比特(所有连续与相同的贝尔特比特状态)和计算他们的间隔
请注意:此表包含数百万条记录,因此多个连接将非常缓慢
我发现这样的查询使用sql-2012滞后和超前函数请告诉我是否有任何增强功能
二级
如果没有正确的索引,则多个联接的速度会很慢,因此需要扫描表。调优包括创建正确的索引。我认为可以使用分区而不使用连接来解决这个问题
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
; 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 ),
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