如何从mysql列中减去最高和最低值的平均值

时间:2013-09-03 19:56:54

标签: php mysql

我很难过。我希望获得“帖子”中的平均“点击次数”,但是当我想要显示点击次数高于平均值的所有帖子时,我会想要将最高价值扔掉,以至于它会偏低阈值。出于同样的原因,我也想丢弃最低值。我的代码是:

//get the sum of the clicks from all posts    

$gettotalsum = mysql_query("SELECT sum(clicks) AS click_total FROM posts WHERE clicks > '0' "); 

$clicksum = @mysql_fetch_array($gettotalsum);


//get the number of posts that have clicks                      
$postcount = mysql_query("SELECT postid FROM posts WHERE isactive = 'y' AND clicks > '0' "); 

$clickcount = mysql_num_rows($postcount);   

我怀疑上面的两个查询是我需要修改以过滤最高和最低点击值 - 但是如何?

这是我的其余代码fwiw:

//multiply to get the average, then round it off
$average = $clicksum['clicks'] / $clickcount;
$average = round($average); 

//display posts that are equal to or above average

$getposts = mysql_query("SELECT postid, posturl, posttitle, clicks FROM posts WHERE clicks >= $average order by clicks DESC");

    while ($aboveaverageposts = @mysql_fetch_array($getposts)) {

    //code to format output goes here

    }

我怀疑所有这些代码都可以简化,但现在最重要的是我希望过滤最高和最低值。

提前致谢。

2 个答案:

答案 0 :(得分:1)

你需要提出一个简单的算法来决定这个阈值是什么,你不应该假设它只有1列。最好找出一个百分比,比如任何一个条目高于平均值5倍(我们假设你的平均值是5,所以任何25或更多都是垃圾,显然根据你的需要调整它)

SELECT AVG(clicks) AS average_click 
FROM posts 
HAVING clicks < AVG(clicks)*5 

PS:我从内存中写了这个SQL,所以语法可能不完美

答案 1 :(得分:1)

要获得平均值减去最高值和最低值(如标题所示)有点棘手。我想要这个工作:

SELECT (sum(clicks) - max(clicks) - min(clicks)) / (count(*) - 2) as avgclicks
FROM posts
WHERE clicks > '0'

不幸的是,你可能有重复记录的最大和最小值,因此计数将被关闭。这种方法应该有效:

select avg(clicks) as avgclicks
from posts p cross join
     (select max(clicks) as maxclicks, min(clicks) as minclicks
      from posts p
      where clicks > 0
     ) minmax
where clicks > minmax.minclicks and clicks < minmax.maxclicks;

要获得“高于平均水平”点击次数的所有内容,您可以将其放在where子句中:

select p.*
from posts p
where clicks > (select avg(clicks) as avgclicks
                from posts p cross join
                     (select max(clicks) as maxclicks, min(clicks) as minclicks
                      from posts
                      where clicks > 0
                     ) minmax
                where clicks > minmax.minclicks and clicks < minmax.maxclicks
               )