mysql求分位数_给Mysql加自定义函数计算百分位数(percentile)。

百分位数(percentile)的详细定义见百度百科。

在这里我用一个通俗的例子来补充解释, 例如今年有900万人参加了高考,自然有900万个成绩,某个学校计划择优招生分数最高的前900个,那么分数线应该是多少呢,这就涉及到百分位的计算,这个学校录取的百分比就是万分之一,分数线的位置在万分之九千九百九十九,化成百分比就是99.99%,那对应这个百分比位置的具体数值是多少呢,这个说的就是百分位(percentile)。

Mysql中要实现根据若干条记录的某个字段获取指定百分位的值,用常规的自定义函数似乎行不通。我们用C/C++语言写一个mysql插件。

udf_percentile.cc, 这是插件的源代码。

/*

returns the percentile of the values in a distribution

input parameters:

data (real or int)

desired percentile of result, 0-1 (double)

decimals of output (optional, int)

output:

percentile value of the distribution (real)

compiling

gcc -fPIC -Wall -I /usr/include/mysql51/mysql/ -shared -o udf_percentile.so udf_percentile.cc

udf_percentile.so /usr/lib64/mysql/plugin/

registering the function:

CREATE AGGREGATE FUNCTION percentile RETURNS REAL SONAME 'udf_percentile.so';

getting rid of the function:

DROP FUNCTION percentile;

hat tip to Jan Steemann's udf_median function http://mysql-udf.sourceforge.net/

*/

#ifdef STANDARD

#include

#include

#include

#ifdef __WIN__

typedef unsigned __int64 ulonglong;

typedef __int64 longlong;

#else

typedef unsigned long long ulonglong;

typedef long long longlong;

#endif /*__WIN__*/

#else

#include

#include

#endif

#include

#include

#include

#ifdef HAVE_DLOPEN

#define BUFFERSIZE 1024

extern "C" {

my_bool percentile_init( UDF_INIT* initid, UDF_ARGS* args, char* message );

void percentile_deinit( UD

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值