当前位置: 代码迷 >> Sql Server >> 分组去掉相邻重复的记录后求累计时间差解决思路
  详细解决方案

分组去掉相邻重复的记录后求累计时间差解决思路

热度:29   发布时间:2016-04-27 19:10:28.0
分组去掉相邻重复的记录后求累计时间差
分组去掉相邻重复的记录后求累计时间差
字段以及数据是:(表1) 
  Devid Systime state 
  1001 08:30:10 0
1001 09:25:20 0
1001 10:10:10 1 t1 (即第一条state=1的记录) 
  1001 10:10:20 1 
  1001 10:10:40 1 
  1001 10:11:05 0 t2 (即第一条state=0的记录) 
  1001 10:11:30 0 
  1001 10:11:40 1 t3 (即state=0之后第一条state=1的记录) 
  1001 10:12:10 1 
  1001 10:12:21 0 t4 (即state=1之后第一条state=0的记录) 
  1001 10:12:30 0 
  1001 10:12:50 1 t5 (同上) 

  1002 10:10:11 0  
  1002 10:10:23 1 t1' (同上)
  1002 10:10:40 1 
  1002 10:11:05 0 t2' 
  1002 10:11:40 1 t3' 
  1002 10:12:21 0 t4' 
  1002 10:12:30 0
1002 10:15:30 1 t5'
1002 10:16:25 1 t6'

1003 10:10:23 1 t11' (同上)
  1003 10:11:05 0 t12' 
  1003 10:11:20 0 
  1003 10:11:40 1 t13' 
  1003 10:12:21 0 t14' 
  1003 10:12:30 0

要求得到的结果如下: 
  devid systime state totaltime 
  1001 08:30:10 0 0 
  1001 10:13:11 1 (t2-t1)+(t4-t3)+(10*60) //从第一条state=1的开始计算,若最后仅一条state=1,则结果+10分钟
  1002 10:10:11 0 0 
  1002 10:16:25 1 (t2'-t1')+(t4'-t3')+ +(t6'-t5') //若最后连续state=1,则要计算连续state=1的时间差
1003 10:10:23 1 0 
  1003 10:12:30 0 (t12'-t11')+(t14'-t13') 

计算的原理:供参考
去掉相邻state相同的记录,从第一条state=1的开始计算,下一次state=0的时间减去上一次state=1的时间的累积和;
若最后仅一条state=1,则结果+10分钟;若最后几条连续state=1,则要计算连续state=1的时间差。


------解决方案--------------------
SQL code
SQL code---测试数据---if object_id('[tb]') is not null drop table [tb]gocreate table [tb]([value1] int,[value2] int)insert [tb]select 1,12 union allselect 1,13 union allselect 1,23 union allselect 0,14 union allselect 0,15 union allselect 1,16 union allselect 0,23 union allselect 0,22 union allselect 1,21 union allselect 1,12 ---查询---select id=identity(int,1,1),* into # from [tb]select value1,value2 from # t where not exists(select * from # where value1=t.value1 and id=t.id-1)
------解决方案--------------------
SQL code
CREATE TABLE TBTEST(Devid INT,   Systime   VARCHAR(20),   state INT) 
INSERT TBTEST
SELECT  1001  ,  '08:30:10'  ,  0 UNION ALL
SELECT  1001  ,  '09:25:20'  ,  0 UNION ALL
SELECT  1001  ,  '10:10:10 '  ,  1  UNION ALL     
SELECT  1001  ,  '10:10:20'  ,  1 UNION ALL
SELECT  1001  ,  '10:10:40'  ,  1 UNION ALL
SELECT  1001  ,  '10:11:05'  ,  0  UNION ALL       
SELECT  1001  ,  '10:11:30'  ,  0 UNION ALL
SELECT  1001  ,  '10:11:40'  ,  1 UNION ALL     
  相关解决方案