2016-08-15 57 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