如何用SQLite找到第N个百分位数?

时间:2009-07-14 05:27:23

标签: sqlite percentile

我想找到Nth percentile

例如:table:htwt;列:名称,性别,身高,体重

结果:

| gender | 90% height | 90% weight |
| male   |        190 |         90 |
| female |        180 |         80 |

2 个答案:

答案 0 :(得分:15)

sqlite在分析处理方面不强,但如果您的数据不是很大,您可以尝试使用ORDER BYLIMIT 1和计算的OFFSET来模拟百分位数。请注意,OFFSET从零开始,因此您需要将其调整为一个。

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;

答案 1 :(得分:0)

我需要多个百分比(10,20 ... 100%)并使用以下方法解决它:

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;

此解决方案需要SQLite 3.28.0或更高版本的NTILE窗口功能。