How to find Nth percentile with SQLite?
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.
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;