How can I calculate the median of values in SQLite?

前端 未结 5 2241
旧巷少年郎
旧巷少年郎 2020-12-09 02:59

I\'d like to calculate the median value in a numeric row. How can I do that in SQLite 4?

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 03:39

    Dixtroy provided the best solution via group_concat(). Here is a full sample for this:

    DROP TABLE [t];
    CREATE TABLE [t] (name, value INT);
    INSERT INTO t VALUES ('A', 2);
    INSERT INTO t VALUES ('A', 3);
    INSERT INTO t VALUES ('B', 4);
    INSERT INTO t VALUES ('B', 5);
    INSERT INTO t VALUES ('B', 6);
    INSERT INTO t VALUES ('C', 7);
    

    results into this table:

    name|value
    A|2
    A|3
    B|4
    B|5
    B|6
    C|7
    

    now we use the (slightly modified) query from Dextroy:

    SELECT name, --string_list, count, middle,
        CASE WHEN count%2=0 THEN
            0.5 * substr(string_list, middle-10, 10) + 0.5 * substr(string_list, middle, 10)
        ELSE
            1.0 * substr(string_list, middle, 10)
        END AS median
    FROM (
        SELECT name, 
            group_concat(value_string,"") AS string_list,
            count() AS count, 
            1 + 10*(count()/2) AS middle
        FROM (
            SELECT name, 
                printf( '%010d',value) AS value_string
            FROM [t]
            ORDER BY name,value_string
        )
        GROUP BY name
    );
    

    ...and get this result:

    name|median
    A|2.5
    B|5.0
    C|7.0
    

提交回复
热议问题