如何将开始/结束数据的总小时数/天数分组(每天多次输入,有些截止午夜)?

时间:2017-11-11 09:27:26

标签: mysql date datediff

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

我的桌子;

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

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

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

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

请参阅小提琴:http://sqlfiddle.com/#!9/189e21f/38