I am looking for finding a solution to get the lag between two specific events from a table in MSSQL.
The sample data is below.
The result Im looking to obtain is get the duration of a session which is become active from sleep (marked in the same colour). I dont want to include the duration of a session whose stage is changed to active from any other.
Update : Added the sample data with desired output. I dont needs to consider the duration between a session activity which went to active from wait, only sleep to active needs to be calcualted.
create table TestLag (id int, session_id int, activity_time datetime, activity_name nvarchar(10))
INSERT into TestLag Values (1,1,'2021-04-11 10:10:23','active');
INSERT into TestLag Values (2,1,'2021-04-12 10:12:30','sleep');
INSERT into TestLag Values (3,1,'2021-04-13 10:14:11','active');
INSERT into TestLag Values (4,2,'2021-04-14 10:21:21','sleep');
INSERT into TestLag Values (5,3,'2021-04-15 10:25:18','active');
INSERT into TestLag Values (6,2,'2021-04-16 10:25:18','active');
INSERT into TestLag Values (7,2,'2021-04-17 10:31:23','wait');
INSERT into TestLag Values (8,3,'2021-04-18 10:32:10','sleep');
INSERT into TestLag Values (9,1,'2021-04-19 10:35:28','wait');
INSERT into TestLag Values (10,3,'2021-04-20 10:37:50','active');
INSERT into TestLag Values (11,2,'2021-04-20 10:37:55','active');
Desired output
session_id activity_time duration_session_in_sleep_before_active
1 2021-04-12 10:12:30 101
2 2021-04-14 10:21:21 237
3 2021-04-18 10:32:10 340
Thank you,
Peter

