2013-10-10 59 views
1

我有以下問題:我需要在組中的中位數。組中的SQLITE中位數

示例:我有一個網絡,它們之間有多個起點和終點以及多個移動距離。我現在需要每個開始/結束對的中位數。

爲下表:

Start | End | Time 
     A | B | 5 
     A | B | 9 
     A | B | 6 
     B | C | 4 
     B | C | 8 
     C | A | 5 
     C | B | 6 

我想以下結果:

Start | End | Median(Time) 
     A | B | 6 
     B | C | 6 
     C | A | 5 
     C | B | 6 

我已經看到了如何計算中位數在這裏:How can I calculate the median of values in SQLite?,但我不知道如何申請這對羣體。

要創建表使用下面的代碼:

CREATE TABLE "Times" ("Key" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE , "START" TEXT, "END" TEXT, "TIME" INTEGER); 
INSERT INTO "Times" VALUES(1,'A','B',5); 
INSERT INTO "Times" VALUES(2,'A','B',9); 
INSERT INTO "Times" VALUES(3,'A','B',6); 
INSERT INTO "Times" VALUES(4,'B','C',4); 
INSERT INTO "Times" VALUES(5,'B','C',8); 
INSERT INTO "Times" VALUES(6,'C','A',5); 
INSERT INTO "Times" VALUES(7,'C','B',6); 

任何幫助是極大的讚賞。

+0

只需添加'WHERE'條款後,每' FROM ...'! –

回答

0

我不能使它工作(你不能從LIMITOFFSET內訪問外嵌套表接縫),但得到這樣的回答:

SELECT Start, End, AVG(Time) FROM (
    SELECT *, (
     SELECT COUNT() FROM Times AS _ 
     WHERE Start=Times.Start AND End=Times.End AND (Time>Times.Time OR Time=Times.Time AND ROWID>Times.ROWID) 
    )-(
     SELECT COUNT() FROM Times AS _ 
     WHERE Start=Times.Start AND End=Times.End AND (Time<Times.Time OR Time=Times.Time AND ROWID<Times.ROWID) 
    ) AS m FROM Times WHERE m BETWEEN -1 AND 1 
) GROUP BY Start, End;