4

我有一个 mysql 表,如:

id, visitorid, pageid

当访问者访问网站时,它将访问者 ID 和页面 ID 存储为一行。

我正在尝试提取准确访问该网站 X 次的访问者数量。(用于图表)。所以有多少人只访问一页,有多少人访问两页......

到目前为止,我有:

SELECT COUNT(visid),visid FROM vislog GROUP BY visid ORDER BY COUNT(visid) DESC

但我不知道如何进行计数计数的下一部分。

是否可以作为 MySQL 查询?

4

5 回答 5

14

您可以将查询包装在另一个查询中:

SELECT
    cnt      AS page_visits
  , COUNT(*) AS number_of_visitors
FROM
    ( SELECT 
          COUNT(*) AS cnt                --- use: COUNT(DISTINCT page_id)
                                         --- for a different count
      FROM vislog 
      GROUP BY visid
   ) AS grp
GROUP BY cnt 
ORDER BY number_of_visitors ;

或(我认为这对于将数字传递给图表更有意义),删除ORDER BY与放置相同的:

ORDER BY cnt ;
于 2012-10-07T10:32:05.427 回答
10

一种方法是将此查询包装到另一个查询中:

SELECT COUNT(visid) FROM (
    SELECT COUNT(visid) AS cvisid, visid 
      FROM vislog 
  GROUP BY visid 
  HAVING cvisid = 2) AS c

但我认为您需要获取访问的直方图:这可以使用 PHP 完成(假设查询与问题中的相同):

$results = array();
// query preparation skipped, as it's obviously done by the OP himself
while ($row = $sth->fetch()) {
  $count = $row['cvisid'];
  if (isset($results[$count])) {
    $results[$count]++;
  }
  else {
    $results[$count] = 1;
  }
}

或者使用 MySQL 本身:

SELECT cvisid, 
       COUNT(cvisid) AS cnt 
  FROM (
    SELECT visid,
           COUNT(visid) AS cvisid 
      FROM vislog 
  GROUP BY visid ) AS c
GROUP BY cvisid
于 2012-10-07T10:20:41.170 回答
0

尝试使用以下查询

SELECT COUNT(a.page_visits) AS no_of_visitors, a.page_visits AS page_count
FROM(
SELECT COUNT(DISTINCT pageid) AS page_visits
FROM vislog
GROUP BY visid) AS a
GROUP BY a.page_visits;

希望能帮助到你...

于 2012-10-07T10:26:02.750 回答
0

Raina77ow(第二个回复)在他的第三个代码块中返回了一个干净的解决方案

    SELECT cvisid, 
           COUNT(cvisid) AS cnt 
      FROM (
        SELECT visid,
               COUNT(visid) AS cvisid 
          FROM vislog 
      GROUP BY visid ) AS c
    GROUP BY cvisid

谢谢你

于 2015-01-11T14:04:19.997 回答
-11

我可以这样解决:

SELECT cnt, COUNT(cnt) FROM (
    SELECT COUNT(visid) as cnt FROM vislog GROUP BY visid
) x GROUP BY cnt ORDER BY cnt ASC

小事x很重要。

于 2012-10-07T10:44:10.997 回答