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

我在这里看到了如何计算中位数:如何计算 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);

任何帮助是极大的赞赏。

4

1 回答 1

0

我无法使其工作(接缝无法从内部访问外部嵌套表LIMITor OFFSET),但得到了这个答案:

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;
于 2013-10-10T12:54:04.903 回答