如何按特定时间段内的时间间隔进行分组?

时间:2016-06-10 16:04:11

标签: mysql sql period

鉴于以下结构和数据:

user   initial_date           final_date 
'JOHN' '2016-05-05 18:21:51', '2016-05-05 18:50:34'
'JOHN' '2016-05-05 18:51:44', '2016-05-05 19:10:54'

考虑到2016-05-05 00:00:002016-05-05 18:59:59之间的时间段,我需要找出John在这些寄存器中花费了多少分钟:

user   initial_date           final_date             minutes_spent
'JOHN' '2016-05-05 18:20:00', '2016-05-05 18:50:00'  30
'JOHN' '2016-05-05 18:51:00', '2016-05-05 19:10:00'  9

在第二行,结果是9,因为我的搜索时间是18:59:59,所以必须忽略19:00:00之后的时段。

1 个答案:

答案 0 :(得分:2)

Does this work for you:

select timestampdiff(MINUTE, greatest(initial_date,$start_of_range),
 least(final_date,$end_of_range)) from tbl where initial_date between 
 $start_of_range and $end_of_range or 
 final_date between $start_of_range and $end_of_range

?