Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find Nth percentile with SQLite?

I'll like to find Nth percentile.

for example: table: htwt; columns: name, gender, height, weight

result:

| gender | 90% height | 90% weight |
| male   |        190 |         90 |
| female |        180 |         80 |
like image 388
Eric Tan Avatar asked Jul 14 '09 05:07

Eric Tan


2 Answers

sqlite is not strong in analytical processing but if your data is not very large, you can try to emulate percentile with ORDER BY, LIMIT 1 and a calculated OFFSET. Note that OFFSET is zero-based so you need to adjust it by one.

SELECT
  height AS 'male 90% height'
FROM table
WHERE gender='male'
ORDER BY height ASC
LIMIT 1
OFFSET (SELECT
         COUNT(*)
        FROM table
        WHERE gender='male') * 9 / 10 - 1;
like image 70
laalto Avatar answered Oct 31 '22 01:10

laalto


I needed multiple percentages (10, 20 ... 100%) and solved it with:

WITH p AS (SELECT height, NTILE(10) OVER (ORDER BY height) AS percentile
           FROM table
           WHERE gender = 'male')
SELECT percentile, MAX(height) as height
FROM p
GROUP BY percentile;

This solution requires SQLite 3.28.0 or later for the NTILE window function.

like image 36
sasha Avatar answered Oct 31 '22 02:10

sasha