简体   繁体   中英

Calculate time difference based on status change and day change

I am trying to get the online time of riders based on below data but I am unable to cater to the need of changing days. The status = 1 means rider is online and 0 means offline. Sometimes, the riders forget to mark their offline status ie 0 on their shift end but do it the next morning when they have to start a new shift.

在此处输入图像描述

I am using the below query to get the time differences but this query also calculates the time difference between the changing days. I want it to calculate such that if the last status of the day of any rider is not 0, it should automatically take the last login time as logout time.

SELECT
fleet_id, 
login_time, 
logout_time, 
timediff(logout_time, login_time) AS logged_in_time,
(unix_timestamp(logout_time) - unix_timestamp(login_time))/60 AS minutes_logged_in_time
FROM
(SELECT
    fleet_id, 
    creation_datetime AS login_time, 
    coalesce(
      (SELECT creation_datetime 
         FROM tb_fleet_duty_logs t_out 
        WHERE     t_out.fleet_id = t_in.fleet_id 
              AND t_out.creation_datetime >= t_in.creation_datetime
              AND t_out.status = 0
      ORDER BY creation_datetime
        LIMIT 1
      ), 
      creation_datetime
    ) AS logout_time
FROM
    tb_fleet_duty_logs t_in
WHERE
    status = 1
) AS q1
ORDER BY
    fleet_id, login_time

I'll assume that you have some analytic functions available as well as CTEs. I have the impression that status = 0 is a login. If not then reverse the test in the case expression.

with data as (
    select
        fleet_id,
        cast(creation_datetime as date) as dt,
        count(case when status = 0 then 1 end) over (
            partition by fleet_id, cast(creation_datetime as date)
            order by creation_datetime asc) as login_count
    from tb_fleet_duty_logs
)
select fleet_id,
    min(creation_datetime) as login_time,
    max(creation_time) as logout_time,
    /* ... other calculations ... */
from data
group by fleet_id, dt, login_count
order by fleet_id, login_time;

The trick is to count off the number of logins per day per rider using the order of the timestamps. After that you only need to use simple grouping to collapse the pairs of rows (or single rows) into the login/logout times.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM