如何找到 GPS 跟踪器数据中断的开始和停止?
How to find a start and stop od a break in GPS tracker data?
我有来自 GPS 跟踪器的数据。
比方说:
CREATE TABLE IF NOT EXISTS `gps_data` (
`id` int(6) unsigned NOT NULL,
`speed` int(3) unsigned NOT NULL,
`time` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
和一些示例数据:
INSERT INTO `gps_data` (`id`, `speed`, `time`) VALUES
('1', '5', '07:00'),
('2', '10', '07:10'),
('3', '0', '07:20'),
('4', '0', '07:30'),
('5', '0', '07:40'),
('6', '0', '07:50'),
('7', '20', '08:00'),
('8', '40', '08:10'),
('9', '15', '08:15'),
('10', '0', '08:32'),
('11', '0', '08:40'),
('12', '0', '08:52'),
('13', '12', '09:10'),
('14', '0', '09:25');
问题是如何找到速度= 0的第一个和最后一个位置的时间。
所以在我的例子中,我想要这样的东西:
[break_start, break_stop]
[07:20, 07:50]
[08:32, 08:52]
[09:25, NULL]
这里Fiddle为了更好的理解:http://sqlfiddle.com/#!9/d79228/4
我开始尝试的是:
SELECT `time` AS break_start, `time` AS break_stop FROM `gps_data` WHERE `speed`=0;
MySQL 中的一种方法是为每一行分配一个组。该组可以是行前非零值的数量——具有相邻零值的所有行都在同一组中。
在 MySQL 8+ 中,您可以为此使用 window 函数:
select min(time), max(time)
from (select t.*,
sum(speed <> 0) over (order by time) as grp
from t
) t
where speed = 0
group by grp;
在早期版本中,一种方法是相关子查询:
select min(time), max(time)
from (select t.*,
(select count(*)
from t t2
where t2.speed <> 0 and t2.time <= t.time
) as grp
from t
) t
where speed = 0
group by grp;
Here 是 SQL Fiddle.
我有来自 GPS 跟踪器的数据。 比方说:
CREATE TABLE IF NOT EXISTS `gps_data` (
`id` int(6) unsigned NOT NULL,
`speed` int(3) unsigned NOT NULL,
`time` varchar(200) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
和一些示例数据:
INSERT INTO `gps_data` (`id`, `speed`, `time`) VALUES
('1', '5', '07:00'),
('2', '10', '07:10'),
('3', '0', '07:20'),
('4', '0', '07:30'),
('5', '0', '07:40'),
('6', '0', '07:50'),
('7', '20', '08:00'),
('8', '40', '08:10'),
('9', '15', '08:15'),
('10', '0', '08:32'),
('11', '0', '08:40'),
('12', '0', '08:52'),
('13', '12', '09:10'),
('14', '0', '09:25');
问题是如何找到速度= 0的第一个和最后一个位置的时间。
所以在我的例子中,我想要这样的东西:
[break_start, break_stop]
[07:20, 07:50]
[08:32, 08:52]
[09:25, NULL]
这里Fiddle为了更好的理解:http://sqlfiddle.com/#!9/d79228/4
我开始尝试的是:
SELECT `time` AS break_start, `time` AS break_stop FROM `gps_data` WHERE `speed`=0;
MySQL 中的一种方法是为每一行分配一个组。该组可以是行前非零值的数量——具有相邻零值的所有行都在同一组中。
在 MySQL 8+ 中,您可以为此使用 window 函数:
select min(time), max(time)
from (select t.*,
sum(speed <> 0) over (order by time) as grp
from t
) t
where speed = 0
group by grp;
在早期版本中,一种方法是相关子查询:
select min(time), max(time)
from (select t.*,
(select count(*)
from t t2
where t2.speed <> 0 and t2.time <= t.time
) as grp
from t
) t
where speed = 0
group by grp;
Here 是 SQL Fiddle.