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

时间:2015-10-09 02:23:15

标签: php mysql

我目前正在监视加班费。我希望显示该员工是否超过了他/她的工作时间。

enter image description here

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

看来你需要使用带有MIN()和MAX()函数的GROUP BY子句,这两个函数都需要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

IF 那些" date"列是时间戳,然后使用TIMESTAMPDIFF()将工作,并使用秒作为传递到SEC_TO_TIME的单位,您获得hh:mm:ii格式的输出

每天#34;"结果见: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

<强> Results

|   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 |