sql - Get Time difference between group of records -


i have table following structure

id         activitytime             status 19        2013-08-23 14:52            1 19        2013-08-23 14:50            1 19        2013-08-23 14:45            2 19        2013-08-23 14:35            2 19        2013-08-23 14:32            1 19        2013-08-23 14:30            1 19        2013-08-23 14:25            2 19        2013-08-23 14:22            2 53        2013-08-23 14:59            1 53        2013-08-23 14:56            1 53        2013-08-23 14:57            1 53        2013-08-23 14:52            2 53        2013-08-23 14:50            2 53        2013-08-23 14:49            2 53        2013-08-23 14:18            2 53        2013-08-23 14:30            1 

i want calculate total time difference each id against status 2. example id 19 stayed on status 2 14:35 14:50 (15 minutes), 14:22 14:30 (8 minutes). total id 19 stayed on status 2 23 minutes. (in both cases considered minimum time status 2 status 1) the problem is how include difference between status different in next row.

for example exclude first record in table status 1 , pick second row. same case status 2. pick minimum time, calculate difference , add them multiple groups of status against each channel.

i have tried using cursor can't seem make work. pretty confident can achieve in c# after getting data , looping through it. wondering if there direct way of getting information without loop. created sql fiddle data, can't seem make work. coming c# background basic knowledge of sql. glad if can me out.

cte (common table expressions) can used specialized temp table. allows (in case) dynamically create row number can later create self join on.

i think looking this:

--create temp table select 19 id,'2013-08-23 14:52' activitytime,1 status #temp union select 19,'2013-08-23 14:50',1 union select 19,'2013-08-23 14:45',2 union select 19,'2013-08-23 14:35',2 union select 19,'2013-08-23 14:32',1 union select 19,'2013-08-23 14:30',1 union select 19,'2013-08-23 14:25',2 union select 19,'2013-08-23 14:22',2 union select 53,'2013-08-23 14:59',1 union select 53,'2013-08-23 14:56',1 union select 53,'2013-08-23 14:57',1 union select 53,'2013-08-23 14:52',2 union select 53,'2013-08-23 14:50',2 union select 53,'2013-08-23 14:49',2 union select 53,'2013-08-23 14:18',2 union select 53,'2013-08-23 14:30',1  --build cte table ;with cte ( select      *,     row_number() on (order  id, activitytime) rownum      #temp )  --query cte table, self joining row 1 row 2 compare. select a.id, sum(datediff(minute,b.activitytime,a.activitytime)) totaltime   cte  left outer join cte b     on a.rownum = b.rownum + 1 , a.id = b.id b.status = 2 group a.id 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -