百分位数(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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __WIN__
typedef unsigned __int64 ulonglong;