PHP函数用于查找MySQL中列的中位数

时间:2013-12-14 06:41:52

标签: php mysql sql median

我有一个数据库 db ,其中有一个表

看起来有点像:

id | val
--------
1  | 45
2  | 35
3  | 23
4  | 49
5  | 67
6  | 12
7  | 0
8  | 87
9  | 46

(这只是一个示例数据集。实际数据集很大。我需要尽可能少地工作。)

我需要找到列 val 的中位数。其实我需要多次使用php函数。

确实存在类似的问题:Simple way to calculate median with MySQL

我在这个问题上尝试了几个答案,但没有一个能为我工作。接受的答案不起作用,因为它过去只使用旧版本的SQL。

PS:它应该适用于许多重复的情况。

1 个答案:

答案 0 :(得分:0)

只是为了好玩我以为我尝试在MySQL中完成所有操作,这里是sqlFiddle

SELECT 
  CASE 
  WHEN MOD((select count(*) as count from t),2)=1 THEN
      (select val from
           (select @row:=@row+1 as row,val
            from t,(select @row:=0)r
            order by val)t1
       where t1.row = CEIL((select count(*) as count from t)/2)
      )
  ELSE
       ((select val from
           (select @row:=@row+1 as row,val
            from t,(select @row:=0)r
            order by val)t1
         where t1.row = (select count(*) as count from t)/2)+
        (select val from
           (select @row:=@row+1 as row,val
            from t,(select @row:=0)r
            order by val)t1
         where t1.row = ((select count(*) as count from t)/2)+1))/2 
  END AS median

只需使用您的表名替换t的出现,请勿更改t1。 此外,如果表没有行,它将返回NULL作为中位数。

此查询可以进一步缩小到以下(sqlFiddle

SELECT @rowCount:=(select count(*) as count from t) AS rowcount,
      (select AVG(val) from
           (select @row:=@row+1 as row,val
            from t,(select @row:=0)r
            order by val)t1
       where t1.row IN (FLOOR((@rowCount+1)/2),
                         CEIL((@rowCount+1)/2)
                        )
      ) as Median

它会返回2列,rowcount列和median列。我把rowcount列放在那里因为我不想像以前的查询一样多次计数。