Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL count of count?

I have a mysql table like:

id, visitorid, pageid

When a visitor hits the website it stores their visitor id and the page id as a row.

I am trying to extract the number of visitors who hit the website exactly X times. (for a chart). so how many visit just one page, how many visit 2 pages...

so far I have:

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

But I don't know how to do the next part of counting the counts.

Is it possible to do as a MySQL query?

like image 240
David19801 Avatar asked Dec 07 '22 11:12

David19801


2 Answers

You can wrap your query inside another one:

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 ;

or (I suppose this makes more sense for passing the numbers to a chart), remove the ORDER BY which is the same as putting:

ORDER BY cnt ;
like image 92
ypercubeᵀᴹ Avatar answered Dec 10 '22 10:12

ypercubeᵀᴹ


One way to do it is to wrap this query into another one:

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

But I think you need to get the histogram of visits: this can be done with PHP (assuming the query is the same as in the question):

$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;
  }
}

Or with MySQL itself:

SELECT cvisid, 
       COUNT(cvisid) AS cnt 
  FROM (
    SELECT visid,
           COUNT(visid) AS cvisid 
      FROM vislog 
  GROUP BY visid ) AS c
GROUP BY cvisid
like image 22
raina77ow Avatar answered Dec 10 '22 11:12

raina77ow