2016-08-15 68 views
0

这基本上是网站访问者的统计脚本。我有这样一个非常简单的表格:计算最常见的值,它发生的次数和不使用重复值

website_ref | ip_address | city | page_viewed 
abc    12.13.14  London  index.php 
abc    12.13.14  London  contact.php 
abc    12.13.14  London  about.php 
abc    10.16.19  Paris  index.php 
abc    33.33.33  Paris  about.php 
abc    44.42.32  London  index.php 
abc    09.09.09  Paris  images.php 

这里有更多的信息在这里玩,但与此问题无关。我想要做的是计算游客网站ref最常见的城市。现在看上面的表格,你可能会认为London,就像我目前的脚本。但是由于我的要求是不正确的,因为伦敦的IP地址是相同的,事实上,顶级城市应该是巴黎,这是IP地址最常见的价值。我希望你明白我想要完成的事情。我还希望该声明可能算的结果也是如此,所以它会显示为:

Most common: Paris (3/5) 

5,占总数的不同IP地址的访客(我已经能搞清楚)。这是我目前正在使用的:

$getCITY = mysqli_fetch_assoc(mysqli_query($conn, "SELECT city, COUNT(city) as count FROM all_website_stats WHERE website_ref = '$website_ref' GROUP BY city ORDER BY COUNT(city) DESC LIMIT 1")); 

$getCITY = $getCITY['city']; 

$getCOUNT = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(distinct ip_address) as count FROM all_website_stats WHERE website_ref = '$website_ref' AND `city` = '$getCITY'")); 
$getCOUNT = $getCOUNT['count']; 

我希望有人能帮助我在这里。

回答

2

我会运行此查询:

select city, count(distinct ip_address) as ips, 
(
    SELECT count(distinct ip_address) 
    from all_website_stats where website_ref = 'abc' 
) as total 
from all_website_stats 
where website_ref = 'abc' 
group by city 
order by ips desc 
limit 1 

得到以下结果:

city | ips | total 
Paris | 3 | 5 

Live demo

+0

曾为完美的,我很高兴这一切都在3单一代码,使事情更容易处理。现场演示也有很多帮助。谢谢您的帮助。 – Snappysites

+0

@Snappysites * <帽尖> * – BeetleJuice