Home > OS >  How to find time spent on each status in sql
How to find time spent on each status in sql

Time:10-24

I want to calculate the time spent on each status for each driver. I have already calculated the time difference but it is stored in the wrong cell against the wrong driver. Please see the data and my approach so far. Thanks in advance

My Data

id driver_id status entry_time
1 200 Offline 27/07/2022 20:49
2 200 Available 27/07/2022 20:53
3 200 On-Delivery 27/07/2022 20:55
4 200 Offline 27/07/2022 20:57
5 201 Offline 27/07/2022 20:33
6 201 Available 27/07/2022 20:36
7 201 On-Delivery 27/07/2022 20:39
8 201 Offline 27/07/2022 20:44

Output I want

id driver_id status entry_time Output(time spend in minutes)
1 200 Offline 27/07/2022 20:49 4
2 200 Available 27/07/2022 20:53 2
3 200 On-Delivery 27/07/2022 20:55 2
4 200 Offline 27/07/2022 20:57 -
5 201 Offline 27/07/2022 20:33 3
6 201 Available 27/07/2022 20:36 3
7 201 On-Delivery 27/07/2022 20:39 5
8 201 Offline 27/07/2022 20:44 -
select 
id,
driver_id,
driver_status,
driver_status.entry_time as cur_time,
LEAD(driver_status.entry_time) over (order by driver_status.id)  as next_time,
DATEDIFF(minute,driver_status.entry_time,lead(driver_status.entry_time) over (order by id))  as timespent in minutes
from driver_status;

CodePudding user response:

Your calls to the LEAD() analytic function need a PARTITION clause:

SELECT
    id,
    driver_id,
    driver_status,
    entry_time AS cur_time,
    LEAD(entry_time) OVER (PARTITION BY driver_id ORDER BY entry_time) AS next_time,
    DATEDIFF(minute,
             entry_time,
             LEAD(entry_time) OVER (PARTITION BY driver_id ORDER BY entry_time)
    ) AS [timespent in minutes]
FROM driver_status
ORDER BY
    driver_id,
    entry_time;
  • Related