计算日期之间的总时差(datediff)

时间:2018-01-31 09:30:45

标签: mysql

寻找一种如何计算两个日期之间的“使用”时间的方法。 用法由两个条目定义:start和stop,例如:

1   start   2018-01-10 10:11:00
2   foo     2018-01-11 09:15:00
3   stop    2018-01-11 20:10:00
4   start   2018-01-13 10:11:00
5   foo     2018-01-13 09:15:00
6   foo     2018-01-14 01:10:00
7   stop    2018-01-14 13:10:00
8   start   2018-01-16 15:51:00
9   foo     2018-01-16 04:45:00
10  foo     2018-01-17 03:30:00
11  stop    2018-01-18 15:20:00

我正在寻找一个mysql查询,以获得2018-01-13 10:11:00和2018-01-18 15:20:00之间的总使用时间,所以我希望得到:

datediff(
    4   start   2018-01-13 10:11:00
    7   stop    2018-01-14 13:10:00
)
+
datediff(
    8   start   2018-01-16 15:51:00
    11  stop    2018-01-18 15:20:00
)

1 个答案:

答案 0 :(得分:0)

在此处找到解决方案:MySql - calculate time difference for multiple rows

select to_seconds((
  select t2.job_started
  from JobTable t2
  where t2.job_started > t1.job_started
    and date(t2.job_started) <= '2016-07-31'
  limit 1
)) - to_seconds(t1.job_started) as interval_seconds
from JobTable t1
where date(t1.job_started) >= '2016-07-01'
  and date(t1.job_started) <= '2016-07-31'
  and t1.job_started <> (
    select job_started
    from JobTable
    where date(job_started) <= '2016-07-31'
    order by job_started desc
    limit 1
  )
;

感谢所有表示不可能并且低估了问题的人,你真的在​​帮助!