简体   繁体   中英

MySQL group by multiple with average and distinct conditions

I am trying to combine multiple conditions within a single MySQLi statement, which should calculate the average number of visitors monthly from a visitor log database which records every IP address to each page of each website on the server.

This is slightly more difficult as it requires using a DISTINCT function to separate multiple IP Addresses recorded visiting different pages of the same website, rather than counting that as 2 or more individual visitors.

Here is a screenshot of the database table: 在此处输入图片说明

I have attempted the following script but seem to receive no output?

$getAVERVISITORS = mysqli_fetch_assoc(mysqli_query($conn, "SELECT AVG(count(distinct ip_address)) as average_monthly_visitors FROM all_website_stats WHERE website_ref = '$account_ref' GROUP BY MONTH(date_last_viewed)"));

 $getAVERVISITORS = $getAVERVISITORS['average_monthly_visitors'];

The results need to be grouped by month within date_last_viewed to display how many distinct IP addresses visited a particular website_ref on average each month?

I'm hoping this makes sense enough for somebody to explain where I might be going wrong?

You basically have it except you can't do the avg() in the same line. You need to do a subquery then avg the result. Something like this should work:

SELECT AVG(counter) AS average_monthly_visitors from (SELECT count(distinct(ip_address)) as counter FROM all_website_stats WHERE website_ref = '$account_ref' GROUP BY MONTH(date_last_viewed)) Temp;

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