我有2个不同的表,称为观察和间隔。
意见:
id, type, start
----------
1 classroom 2017-06-07 16:18:40
2 classroom 2017-06-01 15:12:00
----------
间隔:
id, observation id, number, task, time
----------
1 1 1 1 2017-06-07 16:18:48
2 1 2 0 2017-06-07 16:18:55
3 1 3 1 2017-06-07 16:19:00
4 2 1 3 2017-06-01 15:12:10
5 2 2 1 2017-06-01 15:12:15
----------
我想要一个会显示的视图:
observation_id
time_on_task (total time in seconds where task = 1)
----------
1 13
2 5
----------
所以我必须首先检查第一个观察是否有task = 1,如果是,我必须记录当前间隔和观察表中的开始之间的差异,然后将其添加到总时间。从那里开始,如果任务= 1,我只是添加当前间隔和前一个间隔的时差。
我知道我可以使用TIMESTAMPDIFF()或TIMEDIFF()来获取日期的差异。
我相信我必须使用内部联接,但不知道处理此查询的最佳方法。任何帮助将不胜感激。
答案 0 :(得分:0)
您可以使用此查询获得预期的输出。
select observation_id, TIME_TO_SEC(TIMEDIFF(max(time),min(time)))
from your_table
group by observation_id
根据评论编辑添加:
set @preObservationid= 0;
set @row_number= 0;
set @preTime = '';
select observation_id ,
sum(if(rownumber = 1, TIME_TO_SEC(TIMEDIFF(time,start)) ,TIME_TO_SEC(TIMEDIFF(time,pretime))))
from
( select observation_id, task, rownumber, time, start ,pretime
from ( select observation_id, task, time, start, @preTime as pretime, @preTime:= time,
if(@preObservationid = observation_id, @row_number:= @row_number + 1, @row_number:= 1) as rownumber ,
@preObservationid := observation_id
from observations o join intervals i on o.id = i.observation_id
order by observation_id,time ) innertable
where task = 1 ) final
group by observation_id
我希望这会对你有所帮助。让我解释逻辑。