18

我想找到第 N 个百分位数

例如:表:htwt;列:姓名、性别、身高、体重

结果:

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

2 回答 2

20

sqlite 的分析处理能力不强,但如果你的数据不是很大,你可以尝试用 和计算来模拟ORDER BY百分LIMIT 1位数OFFSET。请注意,它OFFSET是从零开始的,因此您需要将其调整为 1。

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;
于 2009-07-14T05:47:31.497 回答
3

我需要多个百分比(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 窗口函数。

于 2020-08-05T16:48:09.847 回答