【问题标题】:Calculate most common value, amount of times it occurs and without using reoccurring values计算最常见的值,它出现的次数并且不使用重复出现的值
【发布时间】:2016-08-15 19:22:16
【问题描述】:

这基本上是网站访问者的统计脚本。我有一个非常简单的表格,如下所示:

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

这里有更多信息,但与这个问题无关。我要做的是计算访问者对网站参考的最常见城市。现在看看上面的表格,你可能会想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'];

我希望有人可以在这里帮助我。

【问题讨论】:

    标签: php mysqli count distinct


    【解决方案1】:

    我会运行这个查询:

    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

    【讨论】:

    • 工作完美,我很高兴它是一个代码中的所有 3 个,使事情更容易处理。现场演示也提供了很多帮助。感谢您的帮助。
    • @Snappysites
    猜你喜欢
    • 2015-05-07
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多