2012-05-09 93 views
0

我有以下問題:我有一個網絡,頂點和邊緣,車輛在四處移動。每當車輛到達頂點時,當前時間戳以及頂點和車輛ID都被記錄到數據庫中。我需要一個具有時間差的表格,在兩個頂點之間需要車輛。使用數據庫表的時間列來生成開始和結束時間

注意:條目以時間戳記升序記錄,但不一定是car_ids或crossing_ids。

實施例:

| 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

我沒有確切的sqlite的語法,但我會分兩步處理這個...

  1. 把數據放到一個遊標或臨時表在爲了你需要它

    SELECT Car_id, Crossing_id, TIMESTAMP FROM Example ORDER BY Car_id ASC, Crossing_id ASC

  2. 遍歷行中crossing_id_start的注nd crossing_id_end,只要當前記錄的car_id與前一記錄相同,其中crossing_id_start變爲crossing_id_end。

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 
相關問題