How can I calculate the median of values in SQLite?

前端 未结 5 2242
旧巷少年郎
旧巷少年郎 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:37

    There is an extension pack of various math functions for sqlite3. It includes group functions like median.

    It will be more work getting this going than CL's answer, but might be worthwhile if you think you will need any of the other functions.

    http://www.sqlite.org/contrib/download/extension-functions.c?get=25

    (Here is the guide for how to compile and load SQLite extensions.)

    From description:

    Provide mathematical and string extension functions for SQL queries using the loadable extensions mechanism. Math: acos, asin, atan, atn2, atan2, acosh, asinh, atanh, difference, degrees, radians, cos, sin, tan, cot, cosh, sinh, tanh, coth, exp, log, log10, power, sign, sqrt, square, ceil, floor, pi. String: replicate, charindex, leftstr, rightstr, ltrim, rtrim, trim, replace, reverse, proper, padl, padr, padc, strfilter. Aggregate: stdev, variance, mode, median, lower_quartile, upper_quartile.

    UPDATE 2015-04-12: Fixing "undefined symbol: sinh"

    As has been mentioned in comments, this extension may not work properly despite a successful compile.

    For example, compiling may work and on Linux you might copy the resulting .so file to /usr/local/lib. But .load /usr/local/lib/libsqlitefunctions from the sqlite3 shell may then generate this error:

    Error: /usr/local/lib/libsqlitefunctions.so: undefined symbol: sinh
    

    Compiling it this way seems to work:

    gcc -fPIC -shared extension-functions.c -o libsqlitefunctions.so -lm
    

    And copying the .so file to /usr/local/lib shows no similar error:

    sqlite> .load /usr/local/lib/libsqlitefunctions
    
    sqlite> select cos(pi()/4.0);
    ---> 0.707106781186548
    

    I'm not sure why the order of options to gcc matters in this particular case, but apparently it does.

    Credit for noticing this goes to Ludvick Lidicky's comment on this blog post

提交回复
热议问题