简体   繁体   中英

Count with group by multiple column

I need to find stastistics of my website, I want to know how many unique views are there in a day and from which tier country.

I am doing this way.

There are two columns ip and tier from which I need to fetch counts

Column ip has ip of visitors.

Column tier has values as int 1,2,3,4,5 for tier1,tier2,tier3,tier4,tier5 countries respectively.

I need to fetch counts of unique ip's and then get respective tiers counts

$date1 = "4-3-2016 00:00:00";
$date2 = "5-3-2016 00:00:00";
$today = strtotime("midnight", strtotime($date1));
$nextday = strtotime("midnight", strtotime($date2));
$query="
SELECT 
COUNT(*) AS `unique`
FROM `stats` 
WHERE (`date`>='$today' AND `date`<'$nextday')  
GROUP BY `ip`, `tier` ORDER BY `tier` DESC;
";

This give me output as

mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 1411 [type] => 0 ) 

I am getting ony unique counts from this, I need to get tiers count too.

There is this approch too

//adding in main query to get tiers counts
COUNT(DISTINCT CASE WHEN `tier` = '1' THEN `ip` END) `tier1`

But this is slow, I want to do it by group by if its possible.

Please suggest any possible way to do this.

Thanks

This would give you count of unique ips respective to tier

SELECT tier, COUNT(ip) AS IP_COUNT FROM
(SELECT DISTINCT tier, ip 
FROM stats
WHERE <your conditions>) A
GROUP BY tier

The total count of ips would be the total sum of all IP_COUNT

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