前2天,老板有个报表需求,需要用到中位数算法。而MYSQL没有直接提供median()这样的直接算中位数的算法。于是就在百度上百度了下。看到有为朋友提供了一种算法。但是只要代码,没有解释。花了挺久的时间,终于理解了这种算法的含义。
源代码如下:
create table state_mid
as
select user_id,avg(price)
from (
select e.user_id, e.price
from
producte e, producte d
where e.user_id = d.user_id
group by e.user_id, e.price
having sum(case when e.price = d.price then 1 else 0 end)>=
abs(sum(sign(e.price - d.price)))
)t
group by user_id。
首先,向写出这位代码的前辈致敬。
这段代码的精髓地方,就在于
having sum(case
when e.price = d.price then 1 else 0 end)>= abs(sum(sign(e.price -
d.price)))
理解这段代码,其实就是理解了中位数的一个体征:
1、当一列数列的数量N是奇数的时候。则中位数的那个数字在数列中的数量>=中位数减去所有数字的结果的符号值(1,0,-1中的一个)的和的绝对值。
简单的例子:
例:数列为1