我有以下问题:我有一个带有顶点和边缘的网络,车辆在这里移动。每当车辆到达顶点时,当前时间戳以及顶点和车辆ID将被记录到数据库中。我需要一张表格,其中包含车辆在两个顶点之间所需的时差。
注意:条目以时间戳递增记录,但不一定是car_ids和crossing_id。
示例:
| ID | Car_id | Crossing_id | TIMESTAMP |
| 1 | 1 | 1 | 2010-09-25 05:20:00 |
| 2 | 1 | 2 | 2010-09-25 05:23:00 |
| 3 | 2 | 1 | 2010-09-25 05:25:00 |
| 4 | 1 | 3 | 2010-09-25 05:35:00 |
| 5 | 2 | 5 | 2010-09-25 05:42:00 |
通缉结果:
| Car_id | Crossing_id_start | Timestamp_start | Crossing_id_end | Timestamp_end |
| 1 | 1 | 2010-09-25 05:20:00 | 2 | 2010-09-25 05:23:00 |
| 1 | 2 | 2010-09-25 05:23:00 | 3 | 2010-09-25 05:35:00 |
| 2 | 1 | 2010-09-25 05:25:00 | 5 | 2010-09-25 05:35:00 |
示例测试数据:
DROP TABLE IF EXISTS "test";
CREATE TABLE "test" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE , "car_id" TEXT NOT NULL , "crossing_id" TEXT NOT NULL , "time" DATETIME);
INSERT INTO "test" VALUES(1,'car_1','crossing_1','2010-09-25 05:20:00');
INSERT INTO "test" VALUES(2,'car_1','crossing_2','2010-09-25 05:23:00');
INSERT INTO "test" VALUES(3,'car_2','crossing_1','2010-09-25 05:25:00');
INSERT INTO "test" VALUES(4,'car_1','crossing_3','2010-09-25 05:35:00');
INSERT INTO "test" VALUES(5,'car_2','crossing_5','2010-09-25 05:42:00');
非常感谢任何帮助;最喜欢的是sqlite,但欢迎任何其他sql数据库的提示!
提前致谢, 杉
答案 0 :(得分:0)
我没有确切的sqlite语法,但我会分两步处理...
按照您需要的顺序将数据放入游标或临时表中
SELECT Car_id, Crossing_id, TIMESTAMP FROM Example ORDER BY Car_id ASC, Crossing_id ASC
迭代填充cross_id_start和crossing_id_end的行,只要当前记录的car_id与前一条记录相同,cross_id_start就会成为crossing_id_end。
答案 1 :(得分:0)
一种可能的解决方案,如果您知道数字将是连续的
select
t1.ID as Car_id,
t1.Crossing_id as Crossing_id_start,
t1.TIMESTAMP as Timestamp_start,
t2.Crossing_id as Crossing_id_end,
t2.TIMESTAMP as Timestamp_end
from table t1
join table t2 on t1.ID = t2.ID and t1.Crossing_id = t2.Crossing_id + 1
order by Crossing_id_start, Crossing_id_end