简体   繁体   中英

How to select unique visitors per date interval?

I've found a few query strings related to what I'm looking for, but nothing that does this. Basically, I have a graph that needs to display unique visitors per time interval (hour, day, month, or year). So, a graph similar to Google Analytics or this Analytics Graph . The table has a visitor ID column and a timestamp column (in the style 0000-00-00 00:00:00). I need to be able to select the unique or total visitors per interval (eg. 32 visitors on the 5th, 30 on the 6th, etc).

I guess my question is, is there anyway to do this efficiently with just a query? Or will I need to use PHP to get all the data (problem with that is that I would have to do a query for each point on the graph, not efficient)?

You will need to aggregate your data. Try this query:

SELECT DATE(data_timestamp), COUNT(visitor_id)
FROM analytics_table
WHERE DATE(data_timestamp) BETWEEN '2011-05-01' AND '2011-05-31'
GROUP BY 1

Here's how you populate your monthly data ( WARNING: UNTESTED! ):

<?php
$sql = "SELECT DATE(data_timestamp), COUNT(visitor_id)
FROM analytics_table
WHERE DATE(data_timestamp) BETWEEN '2011-05-01' AND '2011-05-31'
GROUP BY 1";

$rs = mysql_query($rs);
$date1 = $datex = '2011-05-01';
$date2 = '2011-05-31';

$arrayData = $tmpArray = array();

while( $r = mysql_fetch_array($rs) )
{
   $tmpArray[$r['date']] = $r['count'];
}

while( $datex <= $date2)
{
   if( isset($tmpArray[$datex]) )
   {
      $arrayData[$datex] = $tmpArray[$datex];
   }
   else
   {
      $arrayData[$datex] = 0;
   }
   list( $y, $m, $d) = explode('-', $datex);
   $datex = date('Y-m-d', mktime(0, 0, 0, $m, $d, $y));
}


?>

this query use:

  • DATE() to get the date from your data and
  • COUNT() to count total data from that particular date.
  • and GROUP BY to group your data based on what field you select.

Basically, you can cast the DATETIME/TIMESTAMP into dates, and times separately, and then use a GROUP BY to get the results you need.

MySQL/SQL: Group by date only on a Datetime column

GROUP BY doesn't return 0 value if there is no visitor some day. That will yield to the holes in time continuity. There are two ways:

1) Group like others said and then find holes

2) Create aggregation table with fields "date", "count" etc. and insert there data every day by cron.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM