如何对 start/finish 数据的总数 hours/day 进行分组(每天多次输入,有些穿越午夜)?

How to group total hours/day for start/finish data (multiple entries per day, some crossing midnight)?

我想知道如何获取当前日期中两个日期之间的确切小时数。

我的table;

id | start      | s_clock   | finish      | f_clock
---------------------------------------------------
1  | 2017-11-10 | 22:00     | 2017-11-11  | 03:00
2  | 2017-11-11 | 09:00     | 2017-11-11  | 10:00

预期结果:

day        | total_hours 
--------------------------
2017-11-10 | 02:00            -- sum of all hours spent on 2017-11-10
2017-11-11 | 04:00            -- sum of all hours spent on 2017-11-11

感谢您的帮助。

您应该避免使用 reserved keywords 作为 table 或字段名称。

start就是其中之一。

create table times ( startt date, s_time time, finish date, f_time time);

insert into times
values 
( "2017-11-10" , "22:00", "2017-11-11" , "03:00"),
( "2017-11-11" , "09:00", "2017-11-11" , "10:00");

select time(sum(delta_on_day)),on_day  -- comment line to see ungrouped results
from -- comment line to see ungrouped results
(   -- comment line to see ungrouped results
  (
    select * 
    ,  timediff(time("24:00"), s_time)  as delta_on_day       
    ,  startt as on_day  
    from times 
    where startt < finish
  )
  UNION ALL 
  (
    select * 
    ,  timediff(f_time, time("0:0"))  as delta_on_day       
    ,  finish as on_day  
    from times 
    where startt < finish
  )
  UNION ALL 
  (
    select * 
    ,  timediff(f_time, s_time)  as delta_on_day       
    ,  startt as on_day  
    from times 
    where startt = finish
  )
) as tbl -- comment line to see ungrouped results
group by on_day -- comment line to see ungrouped results

参见fiddle:http://sqlfiddle.com/#!9/189e21f/38