繁体   English   中英

如何获得 MySQL 中两个不同行的 timediff?

[英]How can i get the timediff of two different rows in MySQL?

我目前正在监控加班情况。 我想显示该员工是否超过了他/她的工作时间。

在此处输入图片说明

首先想到的是,将 In 和 Out 值存储为时间戳,以便您可以轻松地减去整数并获得差异。

看来您需要将 GROUP BY 子句与 MIN() 和 MAX() 函数一起使用,这两个函数都需要 case 表达式来确定 In 或 Out 日期。

SELECT
      empid
    , MIN(CASE WHEN `type` = 'In' THEN `date` END)
    , MAX(CASE WHEN `type` = 'Out' THEN `date` END)
    , SEC_TO_TIME(TIMESTAMPDIFF(SECOND,MIN(CASE WHEN `type` = 'In' THEN `date` END),MAX(CASE WHEN `type` = 'Out' THEN `date` END)))
FROM yourtable
GROUP BY
      empid

如果这些“日期”列是时间戳,那么使用 TIMESTAMPDIFF() 将起作用,并且通过使用秒作为传递给 SEC_TO_TIME 的单位,您将获得 hh:mm:ii 格式的输出

对于“每天”结果,请参阅: SQL Fiddle

create table logs (Pin varchar(20),
                   Mode varchar(100),
                   Date_time datetime);

insert into logs values ('16514','IN','2015-06-12 16:37:46');
insert into logs values ('16514','OUT','2015-06-13 06:37:46');
insert into logs values ('16514','IN','2015-06-13 16:37:46');
insert into logs values ('16514','OUT','2015-06-14 06:37:46');

查询 1

select
       pin
     , in_datetime
     , out_datetime
     , date_format(SEC_TO_TIME(TIMESTAMPDIFF(SECOND,in_datetime,out_datetime)),'%H:%i:%S') as duration
from (
      select
            pin
          , date_time as in_datetime
          , (select l.date_time from logs as l
             where l.date_time > logs.date_time
             and l.mode = 'OUT'
             order by l.date_time ASC
             LIMIT 1) as out_datetime
      from logs
      where mode = 'IN'
    ) as relog

结果

|   pin |            in_datetime |           out_datetime | duration |
|-------|------------------------|------------------------|----------|
| 16514 | June, 12 2015 16:37:46 | June, 13 2015 06:37:46 | 14:00:00 |
| 16514 | June, 13 2015 16:37:46 | June, 14 2015 06:37:46 | 14:00:00 |

暂无
暂无

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

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