MYSQL count of count?

后端 未结 5 2100
执笔经年
执笔经年 2020-12-10 19:36

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.

相关标签:
5条回答
  • 2020-12-10 20:04

    Raina77ow (2nd reply) returned a clean solution in his third block of code

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

    thank you

    0 讨论(0)
  • 2020-12-10 20:04

    I could solve it this way:

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

    The little x is important.

    0 讨论(0)
  • 2020-12-10 20:06

    Try using following query

    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;
    

    Hope it helps...

    0 讨论(0)
  • 2020-12-10 20:25

    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
    
    0 讨论(0)
  • 2020-12-10 20:27

    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 ;
    
    0 讨论(0)
提交回复
热议问题