简体   繁体   English

根据状态变化和日期变化计算时差

[英]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. status = 1 表示骑手在线,0 表示离线。 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.有时,骑手忘记在他们的班次结束时标记他们的离线状态,即 0,但在第二天早上他们必须开始新班次时这样做。

在此处输入图像描述

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.我希望它计算为如果任何骑手当天的最后状态不为 0,它应该自动将最后一次登录时间作为注销时间。

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.我假设您有一些可用的分析函数和 CTE。 I have the impression that status = 0 is a login.我的印象是status = 0是登录。 If not then reverse the test in the case expression.如果不是,则反转case表达式中的测试。

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.之后,您只需要使用简单的分组将成对的行(或单行)折叠到登录/注销时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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