I have a table that contains information of a users work status on a mobile device. Every time their status changes, a new row is created, with their original status before the change, and what their new status now is. The table looks like this:
ID Date_Time User OriginalStatus NewStatus
---------------------------------------------------------------------------
60713 2017-04-11 12:14:42 Helen Not Started Active
60714 2017-04-11 12:19:20 Monica Active Paused
60715 2017-04-11 12:20:43 Dave Active Paused
60716 2017-04-11 12:32:18 Helen Finished Archived
60717 2017-04-11 12:48:57 Monica Paused Active
60718 2017-04-11 12:52:35 Dave Paused Active
What I am trying to do is calculate the duration that each user remains in the 'Paused' status on each date... they are only allowed to move from 'Paused' back to 'Active' which denotes the end of their 'Paused' time, and all other rows can be ignored, and the changes from 'Paused' back to 'Active' will not be in consecutive rows.
In the above example, Monica has remained 'Paused' for 29 minutes and 37 Seconds (12:19:20 to 12:48:57) and Dave has been 'Paused' for 31 minutes and 52 seconds (12:20:43 to 12:52:35).
Ideally I'd like results similar to:
User Paused_Start_Time Paused_End_Time Paused_Duration
---------------------------------------------------------------------------
Monica 2017-04-11 12:19:20 2017-04-11 12:48:57 00:29:37
Dave 2017-04-11 12:20:43 2017-04-11 12:52:35 00:31:52
I'm at a loss to how to go about working this out, so all help gratefully received. I'm using SQL Server 2012.
I think you just need lead()
:
select user, date_time as paused_starttime, next_date_time as paused_endtime
from (select t.*,
lead(date_time) over (partition by user order by date_time) as next_date_time
from t
) t
where status = 'paused';
To get the duration you can subtract the values. However, this returns the interval as a datetime value. You can convert this to a time
, but the time will never be greater than 24 hours. I'm not sure what you want to do when the time exceeds that period.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.