0

我有来自 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]

这是更好理解的小提琴:http ://sqlfiddle.com/#!9/d79228/4

我开始尝试的是:

SELECT `time` AS break_start, `time` AS break_stop  FROM `gps_data` WHERE `speed`=0;
4

1 回答 1

1

MySQL 中的一种方法是为每一行分配一个组。该组可以是行之前的非零值的数量——所有具有相邻零值的行都在同一个组中。

在 MySQL 8+ 中,您可以为此使用窗口函数:

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;

是一个 SQL 小提琴。

于 2018-11-24T14:50:55.423 回答