Select TOP X (or bottom) percent for numeric values in MySQL(为 MySQL 中的数值选择 TOP X(或底部)百分比)
问题描述
我想知道是否有任何函数可以在 MySQL 中用于从包含数值的列中选择前 X(或底部)百分比.
I was wondering if there are any functions that can be used in MySQL to select the TOP X(or bottom) percent from a column containing numeric values.
基本上,我有一列包含价格列表,我只想返回价格前十个百分位数中的那些字段.有什么建议?
Basically, I have a column containing a list of prices and I only want to return those fields in the top ten percentile of prices. Any suggestions?
推荐答案
UPDATE:来自更了解的人 此处.尽管如此,MySQL 中似乎仍然没有嵌入式函数来计算百分位数.
UPDATE: Much more thought-out explanation of the subject from much more knowing person here. Nonetheless, it still seems there's no embedded function in MySQL to calculate percentiles.
试试:
SELECT * FROM价格 WHERE price >= (SELECT 0.9 * max(price) FROM价格)
SELECT price FROM prices p1 WHERE
(SELECT count(*) FROM prices p2 WHERE p2.price >= p1.price) <=
(SELECT 0.1 * count(*) FROM prices)
);
这将给出价格 P1 对于 Price 表中具有 price >= P1 的记录数量将是总数量的十分之一Price 表中的记录.之后:
This will give price P1 for which number of records in Price table having price >= P1 will be one tenth of total number of records in Price table. After that:
SELECT * FROM prices WHERE price >= (SELECT price FROM prices p1 WHERE
(SELECT count(*) FROM prices p2 WHERE p2.price >= p1.price) <=
(SELECT 0.1 * count(*) FROM prices)
);
将返回所有需要的记录.
will return all desired records.
注意:我没有检查这个查询的性能,我认为使用临时表/变量的解决方案必须更有效.
Note: I didn't examine performance of this query, I think solution with temporary table/variable must be more effective.
这篇关于为 MySQL 中的数值选择 TOP X(或底部)百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为 MySQL 中的数值选择 TOP X(或底部)百分比
基础教程推荐
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 是否可以执行按位分组功能? 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
