为 MySQL 中的数值选择 TOP X(或底部)百分比

Select TOP X (or bottom) percent for numeric values in MySQL(为 MySQL 中的数值选择 TOP X(或底部)百分比)
本文介绍了为 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(或底部)百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)