从本质上讲,我想了解产品花费了多少时间。 每个产品都由model_id标识,并且不同的人可以从事 每个产品。我想要产品在使用时与5分钟以上的间隙之间的时间差。
CREATE TABLE test (id INT, created_at DATETIME, model_id INT, TIMEDIFF DATETIME, TOTALTIME DATETIME)
SELECT '144111', '2019-03-30 11:14:26','301302','',''
UNION
SELECT '144112', '2019-03-30 11:14:33','301302','',''
UNION
SELECT '144113', '2019-03-30 11:14:33','301302','',''
UNION
SELECT '144114', '2019-03-30 11:14:54','301302','',''
UNION
SELECT '144115', '2019-03-30 11:15:35','301302','',''
UNION
SELECT '144116', '2019-03-30 11:22:21','301302','',''
UNION
SELECT '144117', '2019-03-30 11:23:14','301302','',''
UNION
SELECT '144118', '2019-03-30 11:24:24','301302','',''
UNION
SELECT '144119', '2019-03-30 11:25:35','301302','',''
WHILE (SELECT COUNT(model_id) FROM portal3_projectsolar.`qat_` WHERE `timediff` IS NULL) > 0 DO #begining of while loop
#min modelid
SET @modelid = (SELECT MIN(model_id) FROM `portal3_projectsolar`.`qat_` WHERE `Timediff` IS NULL);
#set the times
SET @starttime = (SELECT MIN(created_at) FROM `portal3_projectsolar`.`qat_` a WHERE a.model_id = @modelid AND a.`Timediff` IS NULL ORDER BY a.model_id, a.created_at);
SET @endtime = (SELECT MIN(created_at) FROM `portal3_projectsolar`.`qat_` a WHERE a.model_id = @modelid AND a.created_at > @starttime AND a.`Timediff` IS NULL ORDER BY a.model_id, a.created_at);
SET @Nexttime = (SELECT MIN(created_at) FROM `portal3_projectsolar`.`qat_` a WHERE a.model_id = @modelid AND a.created_at > @endtime AND a.`Timediff` IS NULL ORDER BY a.model_id, a.created_at);
# compare the endtime and the nexttime. if nextime is 5 minutes more than endtime then endtime is endtime
WHILE (SELECT DATE_ADD(@endtime,INTERVAL 30 MINUTE) > @Nextdate) DO
SET @Endtime =(SELECT @Nexttime);
SET @Nexttime = (SELECT MIN(created_at) FROM `portal3_projectsolar`.`qat_` WHERE model_id = @modelid AND created_at > @endtime AND `Timediff` IS NULL ORDER BY model_id, created_at);
END WHILE;
#the time diffrence
SET @timediff = (SELECT TIMESTAMPDIFF(MINUTE, @starttime, @endtime));
SET @startid = (SELECT MIN(id) FROM qat_ WHERE created_at = @starttime);
SET @endid = (SELECT MIN(id) FROM qat_ WHERE created_at = @endtime);
#update the time diff for the id range
UPDATE portal3_projectsolar.`qat_`
SET `timediff` = @timediff
WHERE Created_at = BETWEEN @starttime AND @Endtime;
END WHILE;
结果应在timediff列中显示开始和结束的差异,并在totaltime列中显示每个model_id花费的总时间