1

我难住了。我想从“帖子”中获得平均“点击次数”,但丢弃通常很高的最高值,以至于当我想显示所有点击次数高于平均水平的帖子时,它会扭曲阈值。出于同样的原因,我也想丢弃最低值。我的代码是:

//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

    }

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

提前致谢。

4

2 回答 2

1

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

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

PS:这个SQL是凭记忆写的,所以语法可能不完美

于 2013-09-03T20:04:38.830 回答
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
               )
于 2013-09-03T20:26:33.640 回答